简体   繁体   中英

Jackson JSON force deserialize to object

I got a class setup with delegation

public class MyClass implements List<Integer> {

    public String name;

    public List<Integer> target; // this is the delegation target
    // more fields

    @Override
    public Integer get(int index) {
        return target.get(index);
    }
    // all other method in target interface is delegated 
}

And I got a JSON that looks like this:

{"target": [1, 2, 3] , "name":"foo"}

And Jackson throws this:

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.foo.MyClass out of START_OBJECT token
 at [Source: java.io.StringReader@156e5f3e; line: 1, column: 1]
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)
    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:691)
    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:685)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:256)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:214)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:204)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:23)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2986)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2091)

I was speculating that Jackson thought MyClass is a list so didn't know what to do with {} because [] is expected

I confirmed my speculation by making MyClass not implement List<Integer> :

public class MyClass { /*same stuff*/}

And everything worked. But I need MyClass to implement List<Integer> ....

Is there an annotation or configuration in module that I can use to solve this?

我在阅读这篇文章时偶然发现了我的答案。基本上,我需要用我的课程注释

@JsonFormat(shape = Shape.OBJECT)

You can probably write a custom deserializer but I really think the problem will be much better solved if you remove the List inheritance.

What is the requirement to implement that interface? Wouldn't it make more sense for your top level class to have an accessor to the list instead of implementing an interface? From an OO perspective, your top level class is not a "kind of" list. Remove the inheritance and you have a cleaner design that works with Jackson.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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