[alibaba/fastjson]在类型字段不是第一个的情况下,无法反序列化多态对象 Cannot deserialize polymorphic object when the type field is not at the beginning in JSON.

2024-09-02 18 views
1

复现代码:

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson.serializer.SerializerFeature;
public class Main {
    @JSONType(typeKey = "type",seeAlso = {A.class})
    public static interface Base{}

    @JSONType(typeKey = "type", typeName = "A", serialzeFeatures = SerializerFeature.WriteClassName)
    public static class A implements Base {
        int val;

        public A(int val) {
            this.val = val;
        }

        public void setVal(int val) {
            this.val = val;
        }

        public int getVal() {
            return val;
        }
    }

    public static void main(String[] args) {
        Base base = JSONObject.parseObject("{\"val\":1,\"type\":\"A\"}", Base.class);

        System.out.println(base);
    }
}

反序列化结果为null,显然是错误的,JSON对字段顺序不做要求。如果type是第一个则正常。 2.0.18中仍存在该问题。

回答

5

实测2.0.19仍存在该问题

7

Fastjson2 也存在该问题

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.annotation.JSONType;

public class Main {
    @JSONType(typeKey = "type", seeAlso = {A.class})
    public static interface Base{}

    @JSONType(typeName = "A")
    public static class A implements Base{
        public int val;

        public int getVal() {
            return val;
        }

        public void setVal(int val) {
            this.val = val;
        }

        @Override
        public String toString() {
            return "A{" +
                "val=" + val +
                '}';
        }
    }

    public static void main(String[] args) {
        System.out.println(
            JSONObject.parseObject("{\"type\":\"A\",\"val\":1}", Base.class)
        ); // ok

        System.out.println(
            JSONObject.parseObject("{\"val\":1,\"type\":\"A\"}", Base.class)
        ); // outputs null
    }
}
4

实测已修复

5

1.2.86的这个问题是不修复了吗?