JSONObject转为实体类对象

JSONObject js = new JSONObject();
js.put("name", "张三");
js.put("age", 18);
Student student = JSON.toJavaObject(js, Student.class);
Student student1 = JSON.parseObject(String.valueOf(js), Student.class);

注:JSON中的toJavaObject方法和JSONObject中的getObject方法支持深转换,可以转换实体对象;而JSON中的parseObject方法只能转换一层对象;

深转换

以上边代码中的js为例:
深转换的的意思也就是如果在js中再put一个student对象,那么parseObject是不能转换js中的student对象的。


2024-1-24

补充

新增一个知识点:在对json转为实体类对象时,无论json中的数据字段是否多于或少于实体类中字段,转化都不会报错,举个例子

//一个Student实体类,属性包括姓名和年龄
@Data
public class Student {
    private String name;

    private Integer age;
}

写一个转为实体类的代码

  • 情况一:json字段多于实体类字段
public class test {
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "zhangsan");
        jsonObject.put("age", 18);
        jsonObject.put("gender", "male");
        Student student = JSON.parseObject(String.valueOf(jsonObject), Student.class);
        Student student1 = JSON.toJavaObject(jsonObject, Student.class);
        System.out.println(student);
        System.out.println(student1);
    }
}

结果
在这里插入图片描述

  • 情况二:json字段少于实体类字段
public class test {
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "zhangsan");
        //jsonObject.put("age", 18);
        //jsonObject.put("gender", "male");
        Student student = JSON.parseObject(String.valueOf(jsonObject), Student.class);
        Student student1 = JSON.toJavaObject(jsonObject, Student.class);
        System.out.println(student);
        System.out.println(student1);
    }
}

结果
在这里插入图片描述
注:这个点其实挺重要的,这充分说明了一件事,那就是json数据格式的灵活性。

Logo

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

更多推荐