通过Map类和List类的List<Map<>>组合类体会JSON
下面这段 Java 代码使用 JUnit 的 @Test
注解定义了一个测试方法 testMapList
。该方法的主要功能是创建一个包含多个 Map
对象的 List
,并将这些 Map
对象添加到列表中,然后打印列表内容,最后使用 FastJSON
库将列表转换为JSON
字符串、JSON
格式化字符串并打印。
@Test
public void testMapList() {
List<Map<String,Object>> resultList = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
Map<String, Object> map2 = new HashMap<>();
Map<String, Object> map3 = new HashMap<>();
map1.put("键1","值1");
map1.put("键2","值2");
map1.put("键3","值3");
map2.put("键5","值5");
map1.put("键4",map2);
map3.put("键6","值6");
resultList.add(map1);
resultList.add(map3);
System.out.println(resultList);
// 使用 FastJSON 将 resultList 转换为 JSON 字符串
String jsonString = JSON.toJSONString(resultList);
System.out.println(jsonString);
// 使用 FastJSON 将 resultList 转换为格式化的 JSON 字符串,符合阅读习惯
String fomatJsonString = JSON.toJSONString(resultList, SerializerFeature.PrettyFormat);
System.out.println(fomatJsonString);
}
1. 方法定义和初始化
@Test
public void testMapList() {
List<Map<String,Object>> resultList = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
Map<String, Object> map2 = new HashMap<>();
Map<String, Object> map3 = new HashMap<>();
}
List<Map<String,Object>> resultList = new ArrayList<>();
:创建一个List
对象resultList
,用于存储Map
对象。List
的泛型类型是Map<String, Object>
,表示该列表中的每个元素都是一个键为String
类型,值为Object
类型的Map
。- 分别创建三个
Map
对象map1
、map2
和map3
,用于存储键值对。
2. 向 Map
中添加键值对
map1.put("键1","值1");
map1.put("键2","值2");
map1.put("键3","值3");
map2.put("键5","值5");
map1.put("键4",map2);
map3.put("键6","值6");
map1.put("键1","值1");
:向map1
中添加一个键值对,键为"键1"
,值为"值1"
。map1.put("键4",map2);
:将map2
作为值,键为"键4"
放入map1
中。这意味着map1
中的"键4"
对应的值是另一个Map
对象map2
。- 同理,向
map2
中添加"键5"
和"值5"
,向map3
中添加"键6"
和"值6"
。
3. 将 Map
对象添加到 List
中
resultList.add(map1);
resultList.add(map3);
- 将
map1
和map3
添加到resultList
列表中。
4. 打印 List
内容
System.out.println(resultList);
使用 System.out.println
方法打印 resultList
的内容。由于 List
类重写了 toString()
方法,所以会按照 Java 的集合格式输出列表中的元素。
5. 使用 FastJSON
将 List
转换为 JSON 字符串并打印
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.30</version>
</dependency>
// 这里使用了阿里FastJSON库,需要提前导入到maven中
String jsonString = JSON.toJSONString(resultList);
System.out.println(jsonString);
// 使用 FastJSON 将 resultList 转换为格式化的 JSON 字符串,符合阅读习惯
String fomatJsonString = JSON.toJSONString(resultList, SerializerFeature.PrettyFormat);
System.out.println(fomatJsonString);
JSON.toJSONString(resultList);
:使用FastJSON
库的toJSONString
方法将resultList
转换为 JSON 格式的字符串。-
JSON.toJSONString(resultList, SerializerFeature.PrettyFormat);
:使用FastJSON
库的toJSONString
方法将resultList
转换为 JSON 格式化后的字符串。
System.out.println(jsonString);
:打印转换后的 JSON 字符串。
6.打印结果
[{键1=值1, 键4={键5=值5}, 键2=值2, 键3=值3}, {键6=值6}]
[{"键1":"值1","键4":{"键5":"值5"},"键2":"值2","键3":"值3"},{"键6":"值6"}]
[
{
"键1":"值1",
"键4":{
"键5":"值5"
},
"键2":"值2",
"键3":"值3"
},
{
"键6":"值6"
}
]