JSON基本概念
JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于 JavaScript,但可以被多种编程语言使用。JSON 格式易于读写,也易于机器解析和生成。
JSON基本语法
- 对象 (Object):由花括号 {} 包裹,表示一组键值对。每个键值对之间使用冒号 : 分隔,键与值之间使用逗号 , 分隔。
例如:{"name": "Lucy", "age": 20, "gender": "female"}- 数组 (Array):由方括号 [ ] 包裹,表示一组值。每个值之间使用逗号 , 分隔。数组中的元素可以是 JSON 自身的数据类型,也可以是其他类型。
例如:["apple", "banana", "orange"]- 值 (Value):可以是数字,字符串,布尔值,null,数组,对象等。
- 字符串 (String):由双引号 " " 包裹,表示文本值
解析JSON数据
JSON标准数据实例
{
"string": "Hello, world!",
"number": 123.456,
"boolean": true,
"null": null,
"array": [{
"firstName":"Jimmy",
"lastName":"Zhou"
}],
"object": {
"name": "Lucy",
"age": 20
}
}
【 Gson 】
在项目中添加 Gson 库的依赖:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.7</version> </dependency>
实例代码
package site.resellerlanding.controller; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class Example { public static void main(String[] args) { // 此处使用的是上面的JSON标准数据实例 String json = "{ \"string\": \"Hello, world!\", \"number\": 123.456, \"boolean\": true, \"null\": null, \"array\": [{\"id\": \"1001\", \"firstName\": \"Jimmy\",\"lastName\":\"Zhou\"}], \"object\": { \"name\": \"Lucy\", \"age\": 20 } }"; // 创建JsonObject对象 Gson gson = new Gson(); JsonObject jsonObject = gson.fromJson(json, JsonObject.class); // 创建JsonObject对象的另一种方式 // JsonParser parser = new JsonParser(); // JsonObject obj = parser.parse(json).getAsJsonObject(); // 获取 【 String 】类型的值 String string = jsonObject.get("string").getAsString(); // 获取 【 double 】类型的值 double number = jsonObject.get("number").getAsDouble(); // 获取 【 boolean 】类型的值 boolean bool = jsonObject.get("boolean").getAsBoolean(); // null 值在 Gson 中需要特殊处理 Object nullValue = null; if (jsonObject.get("null") != null && !jsonObject.get("null") .isJsonNull()) { nullValue = jsonObject.get("null").getAsString(); } // 获取 【 数组 Array 】类型中的属性的值 JsonObject arrayObj = jsonObject.get("array").getAsJsonArray().get(0) .getAsJsonObject(); String id = arrayObj.get("id").getAsString(); String firstName = arrayObj.get("firstName").getAsString(); String lastName = arrayObj.get("lastName").getAsString(); // 获取 【 对象 Object 】类型中的属性的值 JsonObject innerObj = jsonObject.get("object").getAsJsonObject(); String name = innerObj.get("name").getAsString(); int age = innerObj.get("age").getAsInt(); // 输出结果 System.out.println("string = " + string); System.out.println("number = " + number); System.out.println("bool = " + bool); System.out.println("nullValue = " + nullValue); System.out.println("id = " + id); System.out.println("firstName = " + firstName); System.out.println("lastName = " + lastName); System.out.println("name = " + name); System.out.println("age = " + age); } }