(JSON转换)String与JSONObject、JSONArray、JAVA对象和List 的相互转换

import com.alibaba.fastjson.JSONObject;

一、图解(使用的FastJSON工具库)

二、详解(以 String与对象相互转换 为例)

1、JSONString 与 JSONObject 相互转化

(1)JSONString == > JSONObject

String jsonStr = "{\"key1\":\"value1\"}"; // 反斜杠是java中用于转义特殊字符 " 的

JSONObject jsonObject = JSON.parseObject(jsonStr);

(2)JSONObject ==> JSONString

String jsonStr = jsonObject.toJSONString();

2、JSONString 与 JAVA对象 相互转化

(1)JSONString ==> JAVA对象

// 反斜杠是java中用于转移特殊字符 " 的

String jsonStr = "{\"name\":\"张三\"}";

User user = JSON.parseObject(jsonStr, User.class);

**(2) JAVA对象 ==> JSONString **

String jsonStr = JSON.toJSONString(user);

三、扩展

1、泛型的反序列化(使用 TypeReference 传入类型信息)

Map map = new HashMap();

map.put("key1", "One");

map.put("key2", "Two");

// 转 JSONString

String mapJson = JSON.toJSONString(map);

// 泛型反序列化

Map map = JSON.parseObject(mapJson, new TypeReference>(){});

//List转JSONString

List ids = Arrays.stream("1,2,3".split(",")).collect(Collectors.toList());

JSONObject json = new JSONObject();

json.put("ids", ids);

String jsonString = json.toJSONString();

//JSONString转List

//1.泛型反序列化

JSONObject jsonObject = JSONObject.parseObject(jsonString);

List objectIds = JSONObject.parseObject(jsonObject .getString("ids"), new TypeReference>(){});

//2.JSONObject.parseArray

List arrayIds = JSONObject.parseArray(jsonObject .getString("ids"), String.class);

四、其他

1、把对象,list转成json:

Object obj = new Object();

String objJson = JSONObject.toJSONString(obj);

List list = new ArrayList<>();

String listJson = JSONObject.toJSONString(list);

2、json对象再转成对象或者list

Object obj = JSONObject.parseObject(headJson, Object .class);

List offList = JSONObject.parseArray(offListJson, Object.class);

3、JSONArray转换

1.List转JSONArray

List list = new ArrayList();

JSONArray array= JSONArray.parseArray(JSON.toJSONString(list));

2.JSONArray转List

JSONArray array = new JSONArray();

List list = JSONObject.parseArray(array.toJSONString(), EventColAttr.class);

3.String转JSONArray

String st = "[{name:Tim,age:25,sex:male},{name:Tom,age:28,sex:male},{name:Lily,age:15,sex:female}]";

JSONArray tableData = JSONArray.parseArray(st);

博客: 【String与JSONObject、JSONArray、JAVA对象和List 的相互转换】

相关文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: 

发表评论

返回顶部暗黑模式