
下面这段 Java 代码使用 JUnit 的 @Test 注解定义了一个测试方法 testMapList。该方法的主要功能是创建一个包含多个 Map 对象的 List,并将这些 Map 对象添加到列表中,然后打印列表内容,最后使用 FastJSON 库将列表转换为JSON字符串、JSON格式化字符串并打印。
java
@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. 方法定义和初始化
java
@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 中添加键值对
java
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 中
java
resultList.add(map1);
resultList.add(map3);
- 将
map1和map3添加到resultList列表中。
4. 打印 List 内容
java
System.out.println(resultList);
使用 System.out.println 方法打印 resultList 的内容。由于 List 类重写了 toString() 方法,所以会按照 Java 的集合格式输出列表中的元素。
5. 使用 FastJSON 将 List 转换为 JSON 字符串并打印
xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.30</version>
</dependency>
java
// 这里使用了阿里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.打印结果
cmd
[{键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"
}
]