文章目录
概要
由于在开发过程中从前端或者第三方接口请求的json数据过于复杂且太长导致直接转换数据显示异常,总结由jsonString转为java方便使用的数据。
一、json转map
//jsonString转map
Map<String, String> jsonMap =
JSON.parseObject(jsonString,
new TypeReference<HashMap<String, String>>() {});
//map转换成jsonString
String jsonStr = JSON.toJSONString(jsonMap);
二、json转list
//json转list
JSONArray jary = (JSONArray) json2.get("list");
List<String> jsonArrayToStringList =
JSONObject.parseArray(jary.toJSONString(),String.class);
三、jsonString转JSONObject
JSONObject json = (JSONObject)
JSONObject.parseObject(jsonString);
四、完整代码
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
public class testJson {
private static String jsonString = "{" +
" \"code\": \"0\"," +
" \"data\": {" +
" \"def1\": \"A\"," +
" \"def2\": \"B\"," +
" \"def3\": \"C\"," +
" \"def4\": \"D\"," +
" \"def5\": \"E\"," +
" \"list\": [" +
" {" +
" \"creationtime\": \"2023-12-16\"," +
" \"creator\": \"光头强\"," +
" \"edu\": \"xtu\"," +
" \"email\": false," +
" \"name\": \"熊二\"," +
" \"sex\": 1" +
" }" +
" ]" +
" }," +
" \"msg\": \"ok\"" +
"}";
public static void main(String[] args) {
JSONObject json = (JSONObject) JSONObject.parseObject(jsonString);
JSONObject json2 = (JSONObject) JSONObject.parse(json.get("data").toString());
JSONArray jary = (JSONArray) json2.get("list");
List<String> jsonArrayToStringList = JSONObject.parseArray(jary.toJSONString(),String.class);
for(String str : jsonArrayToStringList) {
Map<String, String> jsonMap = JSON.parseObject(str, new TypeReference<HashMap<String, String>>() {
});
System.out.println(jsonMap.toString());
}
}
}
五、jsonString的字符串类型
{
"code": "0",
"data": {
"def1": "A",
"def2": "B",
"def3": "C",
"def4": "D",
"def5": "E",
"list": [
{
"edu": "xtu",
"email": false,
"sex": 1,
"name": "熊二",
"creator": "光头强",
"creationtime": "2023-12-16",
}
]
},
"msg": "ok"
}
6、导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
7、JSONArray数组转JSONObject
//基于完整代码
JSONArray jary = (JSONArray) json2.get("list");
JSONObject[] jsons = jary.toArray(new JSONObject[0]);