List<Map<String, Object>>与JSON 相互转换
时间: 2024-03-01 21:54:30 浏览: 289
可以使用JSON库来实现List<Map<String, Object>>与JSON之间的相互转换。以下是一个示例代码:
```java
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.Map;
public class JsonUtils {
private static final ObjectMapper mapper = new ObjectMapper();
public static String toJson(List<Map<String, Object>> list) throws Exception {
return mapper.writeValueAsString(list);
}
public static List<Map<String, Object>> fromJson(String json) throws Exception {
return mapper.readValue(json, new TypeReference<List<Map<String, Object>>>() {});
}
}
```
使用示例:
```java
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("name", "张三");
map1.put("age", 18);
Map<String, Object> map2 = new HashMap<>();
map2.put("name", "李四");
map2.put("age", 20);
list.add(map1);
list.add(map2);
// list转json
String json = JsonUtils.toJson(list);
System.out.println(json);
// json转list
List<Map<String, Object>> newList = JsonUtils.fromJson(json);
System.out.println(newList);
```
输出结果:
```
[{"name":"张三","age":18},{"name":"李四","age":20}]
[{name=张三, age=18}, {name=李四, age=20}]
```
注意:在转换时需要引入JSON库,这里使用的是Jackson库,也可以使用其他的JSON库。
阅读全文