JSON字符串转泛型对象
以下问题只仅限于博主自身遇到,不代表绝对出现问题
相关类展示:
参数基类
public class BaseParams {
}
基类
public abstract class AbstractPush<Params extends BaseParams> {
    protected abstract void execute(Params params);
    public void push(String json){
        //todo 分fastjson和fastjson2说明
    }
}
测试类
public class TestPush extends AbstractPush<TestParams>{
    @Override
    protected void execute(TestParams params) {
        System.out.println("params = " + params);
    }
}
测试类的泛型参数
import lombok.Data;
@Data
@Accessors(chain = true)
public class TestParams extends BaseParams{
    private String name;
    private String sex;
    private Integer age;
}
错误案例
不能如下案例这样使用,在FastJson中,写法不报红;在FastJson2中,写法报红
基类#push(String)
public void push(String json){
    Type type = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    Params params = JSONObject.parseObject(json, new TypeReference<Params>(type) {
    });
    this.execute(params);
}
入口类
public class TestFunction {
    public static void main(String[] args) {
        TestPush testPush = new TestPush();
        TestParams testParams = new TestParams();
        testParams.setName("张三").setSex("男").setAge(10);
        testPush.push(JSON.toJSONString(testParams));
    }
}
执行结果:
 
参考网上资料(文末有说明),改进版
使用FastJson去按照以下案例处理,会在对象转JSON时(JSON.toJSONString),转化结果为{};使用FastJson2在不使用Feature配置项也返回{}。只有当配置了Feature才会返回私有属性。
后续博主也无法复现,故在使用TypeReference最好使用FastJson2,且使用Feature配置项来保证不会出现意外情况
转换类(新增)
@Data
public class Convertor<Params extends BaseParams> {
    private Params params;
}
基类#push(String)
public void push(String json){
    Type type = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    Convertor<Params> convertor = JSONObject.parseObject(json, new TypeReference<Convertor<Params>>(type) {},
            JSONReader.Feature.FieldBased);
    this.execute(convertor.getParams());
}
JSONReader.Feature.FieldBased:基于字段反序列化,如果不配置,会默认基于public的field和getter方法序列化。配置后,会基于非static的field(包括private)做反序列化。在fieldbase配置下会更安全
入口类
public class TestFunction {
    public static void main(String[] args) {
        TestPush testPush = new TestPush();
        Convertor<TestParams> convertor = new Convertor<>();
        TestParams testParams = new TestParams();
        testParams.setName("张三").setSex("男").setAge(10);
        convertor.setParams(testParams);
        String s = JSON.toJSONString(convertor, JSONWriter.Feature.FieldBased);
        testPush.push(s);
    }
}
执行结果:
 
参考:
fastJSON,使用TypeReference处理复杂的泛型对象



















