fastjson SerializerFeature.WriteClassName的特性依赖@type的出现顺序,必须第一个,否则会导致异常

8yparm6h  于 2021-11-27  发布在  Java
关注(0)|答案(1)|浏览(293)

在一些场景下,JSON内容的顺序会被底层存储调整,导致@type不是第一个,导致反序列化异常

希望能提供选项,允许反序列化时不依赖@type的顺序

@Test
    public void test2() {
        Dog dog = new Dog();
        dog.dogName = "dog1001";

        String text = "{\"dogName\":\"dog1001\", \"@type\":\"dog\"}";

        JSONObject jobj = JSON.parseObject(text, Feature.SupportAutoType);
        Dog dog1 = (Dog)jobj.toJavaObject(Animal.class);
        assertEquals(dog.dogName, dog1.dogName);

        Dog dog2 = (Dog)JSON.parseObject(text, Animal.class);

        assertEquals(dog.dogName, dog2.dogName);
    }

    @JSONType(seeAlso = {Dog.class, Cat.class})
    public static class Animal {}

    @JSONType(typeName = "dog")
    public static class Dog extends Animal {
        public String dogName;
    }

    @JSONType(typeName = "cat")
    public static class Cat extends Animal {
        public String catName;
    }

相关问题