1.jackson
导包:
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
使用
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("a",1000);
map.put("b",2000);
ObjectMapper mapper = new ObjectMapper();
try {
// map 转 json 字符串
String s = mapper.writeValueAsString(map);
System.out.println(s);
// json 字符串 转 map
Map map1 = mapper.readValue(s, Map.class);
System.out.println(map1);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
2.fastjson
导包:
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
使用
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("a",1000);
map.put("b",2000);
// map 转 json 字符串
String s = JSONObject.toJSONString(map);
System.out.println(s);
// json 字符串 转 map
Map<String,Object> obj = JSON.parseObject(s, Map.class);
System.out.println(obj);
System.out.println("----------------------");
// list 转 json 字符串
String s1 = JSON.toJSONString(map);
System.out.println(s1);
// json 字符串 转 list
List<String> strings = JSON.parseArray(s1, String.class);
System.out.println(strings);
// List<Map<String,Object>>
List<Map<String, Object>> listMap = JSON.parseObject(jsonString, new TypeReference<List<Map<String,Object>>>(){});
}
ok了。
网友评论