Json字符串,JsonObject,Java对象相互转换
1、Java对象类
public class User{ private String name; private Integer age; public User(){} public User(String name,Integer age){ this.name=name; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
2、相互转化
(1)Json字符串<==>JsonObject
//JSONObject转化为JSONStr String jsonStr = JSON.toJSONString(jsonObject); //JSONStr转化为JSONObject JSONObject jsonObject = JSON.parseObject(jsonStr);
(2)Json字符串<==>Java对象
//JavaObject转化为JSONStr String jsonStr = JSON.toJSONString(user); //JSONStr转化为JavaObject Student user= JSON.parseObject(jsonStr, User.class);
(3)JsonObject<==>Java对象
//JavaObject转化为JSONObject JSONObject jsonObject = (JSONObject) JSON.toJSON(user); //JSONObject转化为JavaObject User user= JSON.toJavaObject(jsonObject, User.class);
(4)Java集合<==> JsonObject数组(JSONArray)
//JavaList转化为JSONArray JSONArray jsonArray = (JSONArray) JSON.toJSON(userList); //JSONArray转化为JavaList List<User> students1 = jsonArray.toJavaList(User.class);
(5)Java集合<==>Json字符串
//JavaList转化为JSONStr String jsonStr = JSON.toJSONString(userList); //JSONStr转化为JavaList List<Student> userList= JSON.parseArray(jsonStr, User.class);
(6)Json字符串<==>JSONArray
//JSONArray转化为JSONStr String jsonStr = JSON.toJSONString(jsonArray); //JSONStr转化为JSONArray JSONArray jsonArray = JSON.parseArray(jsonStr);
(7)JSONArray==>JsonObject
JSONObject jsonObject = jsonArray.getJSONObject(0);
标签:JSONStr,jsonStr,Java,String,JSONArray,JsonObject,JSON,Json,User From: https://www.cnblogs.com/faminecls/p/16997246.html