简体   繁体   English

JSON杰克逊多态反序列化

[英]Trivial JSON jackson polymorphic deserialization

Struggling with something which looks like trivial and should work without any problems. 挣扎着看似微不足道的东西,应该可以正常工作。 I have JSON with "@class" property and without knowing it's class on the moment of invocation readValue() want to deserialize it into the object of the class referenced by "@class". 我有带有“ @class”属性的JSON,并且在调用时不知道它的类是readValue()想要将其反序列化为“ @class”引用的类的对象。 What I get back instead is "LinkedHashMap". 相反,我得到的是“ LinkedHashMap”。

@Test
public void toJsonAndBack() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(new Sample("id"));
    assertTrue(json.contains("@class"));
    Sample obj = (Sample)mapper.readValue(json, Object.class);
}

@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS)
static class Sample {
    private String id;

    public Sample() {
    }

    public Sample(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }
}

Sorry, if dup, but couldn't find exactly the same problem. 抱歉,如果是dup,但找不到完全相同的问题。 The most of people have more complicated cases where there is base class, which is also annotated, etc. These cases actually work fine. 大多数人的情况比较复杂,有基类,也有注释,等等。这些情况实际上很好用。

I'm using jackson 2.6.6 我正在使用杰克逊2.6.6

Jackson converts it into LinkedhashMap , so that later, we can you use its convert method to convert given LinkedhashMap into custom Object. Jackson将其转换为LinkedhashMap ,以便稍后,我们可以使用其convert方法将给定的LinkedhashMap转换为自定义Object。 So here you need to add one more step into it. 因此,在这里您需要再增加一个步骤。

Eg: 例如:

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(new Sample("id"));
Object obj = mapper.readValue(json, Object.class);
Sample sample = mapper.convertValue(obj, Sample.class);

So you can preserve this obj somewhere, and can convert it into Sample class at your convenience. 因此,您可以将此obj保存在某个位置,并可以在方便时将其转换为Sample类。

Apparently adding this line makes this test work: 显然添加此行使此测试有效:

mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

In that case annotation on the Sample class is not necessary. 在这种情况下,不需要在Sample类上进行注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM