
1、fastjson
//String --> Json对象 JSONObject jsonObject = JSONObject.parseObject(jsonData); //Json --> String String jsonString = jsonObject.toJSONString();
2、Gson
//String --> Json对象 JsonObject jsonObject = new JsonParser().parse(jsonData).getAsJsonObject(); //JsonObject jsonObject_2 = gson.fromJson(jsonString_2, JsonObject.class); 错误方法 返回为空(非null) //Json对象 --> String Gson gson = new Gson(); String jsonString = gson.toJson(jsonObject);
3、jackson
//String --> Json对象 //暂未知,有知道的大佬请告知 //Json对象 --> String //用到fastJson格式的JSONObject ObjectMapper objectMapper = new ObjectMapper(); String jsonString_3 = objectMapper.writeValueAsString(jsonObject_1);二、Json字符串与map转换
1、fastjson
//字符串 --> map Map map = JSONObject.parseObject(strList, Map.class); //map --> 字符串 String jsonString = JSON.toJSONString(map);
2、Gson
//字符串-->map Gson gson = new Gson(); Map map_2 = gson.fromJson(strList, Map.class); //map-->字符串 Gson gson = new Gson(); String jsonString_2 = gson.toJson(map);
3、jackson
//字符串 --> map ObjectMapper objectMapper = new ObjectMapper(); Map map_3 = objectMapper.readValue(strList, Map.class); //map --> 字符串 String jsonString_3 = objectMapper.writeValueAsString(map);三、Json对象与map转换
1、fastjson
//map转json对象 JSONObject json = new JSONObject(map); //json对象转Map Map map_1 = JSONObject.parseObject(strList, Map.class); //Mapmap_1 = (Map )jsonObject_1; 此方法也行
2、Gson
//map转json对象
Gson gson = new Gson();
String jsonString_2 = gson.toJson(map);
//JsonObject jsonObject_2 = gson.fromJson(jsonString_2, JsonObject.class); 错误方法 返回为空(非null)
JsonObject jsonObject_2 = new JsonParser().parse(jsonString_2).getAsJsonObject();
//json对象转Map
Map map_2 = gson.fromJson(strList, Map.class);
System.out.println("断点");
3、jackson
//map转json对象 //暂未知,有知道的大佬请告知 //json对象转Map ObjectMapper objectMapper = new ObjectMapper(); Map map_3 = objectMapper.readValue(strList, Map.class);四、对象与Json字符串转换
1、fastjson
//对象-->字符串 String str = JSON.toJSONString(user); //字符串-->对象 User user_2 = JSON.parseObject(jsonData, User.class);
2、jackson
//对象-->String ObjectMapper objectMapper = new ObjectMapper(); String str_3 = objectMapper.writeValueAsString(user); //String-->对象 User user_3 = objectMapper.readValue(jsonData, User.class);五、对象集合与Json字符串转换
1、fastjson
//对象集合-->字符串 String users = JSON.toJSONString(userList); //字符串-->对象集合 ListuserList = JSON.parseArray(userList, User.class);
2、jackson
//对象集合 --> 字符串 ObjectMapper objectMapper = new ObjectMapper(); String users_3 = objectMapper.writeValueAsString(userList); //字符串 --> 对象集合 ListuserList_3 = objectMapper.readValue(strList, new TypeReference >() {});
原文地址https://www.cnblogs.com/ciweiyu/p/13649685.html