java fastjson 如何自定义反序列化器

java fastjson如何解决字符串反序列化成对象的时候,多层嵌套时自定义序列化功能
假如有这么两个实体类
类1 学生类

public class Student {
    
    private String name;
    
    private int age;
   
    private Hobby hobby;
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    public Hobby getHobby() {
        return hobby;
    }
    
    public void setHobby(Hobby hobby) {
        this.hobby = hobby;
    }

类2 兴趣爱好类

public class Hobby {
    
    private String hobbyItem;
    
    private double year;
    
    public String getHobbyItem() {
        return hobbyItem;
    }
    
    public void setHobbyItem(String hobbyItem) {
        this.hobbyItem = hobbyItem;
    }
    
    public double getYear() {
        return year;
    }
    
    public void setYear(double year) {
        this.year = year;
    }
}

现在问题来了,我要将字符串反序列化成对象的时候,如何自定义嵌套的那个类(Hobby)的反序列化

下面是我的测试代码,发现压根没生效

    public static void main(String[] args) {
        ParserConfig parserConfig = new ParserConfig();
        parserConfig.putDeserializer(Hobby.class,new CustomDeserializer(parserConfig, Hobby.class));
        JSONObject json=new JSONObject();
        json.put("name","张三");
        json.put("age",18);
        JSONObject hobby=new JSONObject();
        hobby.put("hobbyItem","唱跳rab篮球");
        hobby.put("year",2.5);
        json.put("hobby",hobby);
        Student student = json.toJavaObject(Student.class, parserConfig, 0);
        System.out.println(student);
    }
  1. 引入hutool依赖 cn.hutool hutool-all 5.7.1
  2. 调用
    JSONUtil.toBean(JSONObject json, Class beanClass) 方法

该回答引用自ChatGPT,根据GPT自己验证

img

代码

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import java.lang.reflect.Type;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;

public class HobbyDeserializer implements ObjectDeserializer {

    @Override
    public Hobby deserialze(DefaultJSONParser parser, Type type, Object o) {
        JSONObject jsonObj = parser.parseObject();
        Hobby hobby = new Hobby();
        hobby.setHobbyItem(jsonObj.getString("hobbyItem"));
        hobby.setYear(jsonObj.getDouble("year"));
        return hobby;
    }
}

    public static void main(String[] args) {
        ParserConfig parserConfig = new ParserConfig();
        parserConfig.putDeserializer(Hobby.class, new HobbyDeserializer());
        JSONObject json = new JSONObject();
        json.put("name", "张三");
        json.put("age", 18);
        JSONObject hobby = new JSONObject();
        hobby.put("hobbyItem", "唱跳rab篮球");
        hobby.put("year", 2.5);
        json.put("hobby", hobby);
        Student student = json.toJavaObject(Student.class, parserConfig, 0);
        System.out.println(student);
    }

因为json支持复杂对象的是,这个复杂对象中都是基本变量类型,包括String。