(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<String, Object> map = new HashMap<String, Object>();
map.put("key1", "One");
map.put("key2", "Two");
// 转 JSONString
String mapJson = JSON.toJSONString(map); 
// 泛型反序列化
Map<String, Object> map = JSON.parseObject(mapJson, new TypeReference<Map<String, Object>>(){}); 
//List<String>转JSONString
List<String> ids = Arrays.stream("1,2,3".split(",")).collect(Collectors.toList());
JSONObject json = new JSONObject();
json.put("ids", ids);
String jsonString = json.toJSONString();

//JSONString转List<String>
//1.泛型反序列化
JSONObject jsonObject = JSONObject.parseObject(jsonString);
List<String> objectIds = JSONObject.parseObject(jsonObject .getString("ids"), new TypeReference<List<String>>(){});
//2.JSONObject.parseArray
List<String> arrayIds = JSONObject.parseArray(jsonObject .getString("ids"), String.class);

四、其他

1、把对象,list转成json:

Object obj = new Object();
String objJson = JSONObject.toJSONString(obj);
List<Object> list = new ArrayList<>();
String listJson = JSONObject.toJSONString(list);

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

Object obj = JSONObject.parseObject(headJson, Object .class);
List<Object> offList = JSONObject.parseArray(offListJson, Object.class);

3、JSONArray转换

1.List转JSONArray
List<T> list = new ArrayList<T>();
JSONArray array= JSONArray.parseArray(JSON.toJSONString(list))
2.JSONArray转List
JSONArray array = new JSONArray();
List<EventColAttr> 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 的相互转换】

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐