栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

【无标题】

Java 更新时间:发布时间: 百科书网 趣学号
一、Json字符串与Json对象转换

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);
//Map map_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);
//字符串-->对象集合
List userList = JSON.parseArray(userList, User.class);  

2、jackson

//对象集合 --> 字符串
ObjectMapper objectMapper = new ObjectMapper();
String users_3 = objectMapper.writeValueAsString(userList);
//字符串 --> 对象集合
List userList_3 = objectMapper.readValue(strList, new TypeReference>() {});

原文地址https://www.cnblogs.com/ciweiyu/p/13649685.html

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/956529.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号