Java 实体类与Map、JSONObject之间的互相转化

1.Map和实体类之间的转换

1.1以实体类User 为例
User user = new User();
Map<String,Object> map = new HashMap<>();

1.2Map转为实体类
User user = JSON.parseObject(JSON.toJSONString(map), User.class);

1.3实体类转为Map
Map newMap = JSON.parseObject(JSON.toJSONString(user), Map.class);

2.JSONObject和实体类之间的转换

2.1 以实体类User 为例
User user = new User();
JSONObject jsonObject = new JSONObject();

2.2 JSONObject转为实体类
User user = JSON.parseObject(JSON.toJSONString(jsonObject), User.class);

2.3 实体类转为JSONObject
JSONObject newJSONObject = JSONObject.parseObject(JSONObject.toJSONString(user));
JSONObject newJSONObject = JSON.parseObject(JSON.toJSONString(user), JSONObject .class);
 

1.Java对象—>JSON对象

Student stu = new Student("公众号BiggerBoy", "m", 2);
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(stu);

2.Java对象—>JSON字符串

Student stu = new Student("公众号BiggerBoy", "m", 2);
String stuString = JSONObject.toJSONString(stu);

3.JSON对象—>JSON字符串

 Student stu = new Student("公众号BiggerBoy", "m", 2);
 JSONObject jsonObject = (JSONObject) JSONObject.toJSON(stu);
 String jsonString = jsonObject.toJSONString();

4.JSON对象—>java对象

Student stu = new Student("公众号BiggerBoy", "m", 2);
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(stu);
Student student = JSONObject.toJavaObject(jsonObject, Student.class);

5.json字符串—>JSON对象

String stuString = "{
    
    \"age\":2,\"name\":\"公众号 BiggerBoy\",\"sex\":\"m\"}";
JSONObject jsonObject1 = JSONObject.parseObject(stuString);

6.JSON字符串—>Java对象

String stuString = "{
    
    \"age\":2,\"name\":\"公众号 BiggerBoy\",\"sex\":\"m\"}";
Student student1 = JSONObject.parseObject(stuString, Student.class);

7.JSON字符串—>list<Java对象>

 String stuString = "[{
    
    \"age\":2,\"name\":\"公众号\",\"sex\":\"m\"},{\"age\":18,\"name\":\"BiggerBoy\",\"sex\":\"m\"}]";
 List<Student> studentList = JSONObject.parseArray(stuString, Student.class);

猜你喜欢

转载自blog.csdn.net/weixin_42258334/article/details/124466756