在使用 gson反序列化解析 json 串时,如果 json 中的字段较多(定义对应的 Java Bean 较为麻烦),或者字段的类型较复杂(类型里面又套了类型,如Map<String, List<Person>>
),
那么这时通过定义 Java Bean、将 json 直接转为 Bean 较为麻烦。
转为什么类型?
怎么办呢?将 json 转为 Map 类型,再逐个取出我们需要的字段即可。
如何取出各个字段?
通过Map.get(字段名)
取出即可。
字段取出后,对应 Java 中的什么类型?
- 数字 => Double
- 字符串 => String
- json 对象 => LinkedTreeMap,可以用
Map<String, Object>
接收 - 数组 => ArrayList,可以用
List
接收
代码示例
json 串:
{
"code": 0,
"data": {
"records": [
{
"id": 1,
"title": "第一条",
"content": "hello,world",
"tags": [
"java",
"spring"
]
},
{
"id": 2,
"title": "第二条",
"content": "404 not found",
"tags": [
"network",
"web",
"http"
]
}
],
"total": "274",
"size": "8",
"current": "1"
},
"message": "ok"
}
代码:
Gson gson = new Gson();
String jsonStr = "{\n" +
" \"code\": 0,\n" +
" \"data\": {\n" +
" \"records\": [\n" +
" {\n" +
" \"id\": 1,\n" +
" \"title\": \"第一条\",\n" +
" \"content\": \"hello,world\",\n" +
" \"tags\": [\n" +
" \"java\",\n" +
" \"spring\"\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"id\": 2,\n" +
" \"title\": \"第二条\",\n" +
" \"content\": \"404 not found\",\n" +
" \"tags\": [\n" +
" \"network\",\n" +
" \"web\",\n" +
" \"http\"\n" +
" ]\n" +
" }\n" +
" ],\n" +
" \"total\": \"274\",\n" +
" \"size\": \"8\",\n" +
" \"current\": \"1\"\n" +
" },\n" +
" \"message\": \"ok\"\n" +
"}";
// 先整个转为Map
Map<String, Object> map = gson.fromJson(jsonStr, Map.class);
// 3.json对象 => LinkedTreeMap,可以用Map<String, Object>接收
Map<String, Object> data = (Map<String, Object>) map.get("data");
System.out.println("json对象 => " + map.get("data").getClass());
// 4.数组 => ArrayList,可以用List接收
// 数组中的json对象 => Map
List<Map<String, Object>> recordList = (List<Map<String, Object>>) data.get("records");
System.out.println("数组 => " + data.get("records").getClass());
// 取出第一个对象
Map<String, Object> record = recordList.get(0);
// 1.数字 => Double
System.out.println("数字 => " + record.get("id").getClass());
// 2.字符串 => String
System.out.println("字符串 => " + record.get("title").getClass());
结果:
json对象 => class com.google.gson.internal.LinkedTreeMap
数组 => class java.util.ArrayList
数字 => class java.lang.Double
字符串 => class java.lang.String
如果有帮助的话,可以点个赞支持一下嘛
🙏