<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
- 基本使用
- Map -> json
- json -> Map
private static String map2Json(Map map) {
Gson gson = new Gson();
StringBuilder sb = new StringBuilder();
if (map != null && map.size() > 0) {
// 数据转换 map -> json
sb.append(gson.toJson(map));
}
return sb.toString();
}
private static Map json2Map(String json) {
Gson gson = new Gson();
Map map;
if (json != null && json.length() > 0) {
// 数据转换 json -> map
map = gson.fromJson(json, Map.class);
} else {
map = new HashMap();
}
return map;
}
@Test
public void testJson2Map() {
Map<String, String> map = new HashMap<>();
map.put("name", "孙悟空");
String json = map2Json(map);
System.out.println(json);
Map map1 = json2Map(json);
System.out.println(map1.toString());
}
网友评论