Can not find deserialize for non-concrete Collection type

随声附和 提交于 2019-11-28 11:41:36

问题


I'm using the jackson library to map JSON into objects. I've simplified the problem a lot, this is what happens:

public class MyObject{

    public ForeignCollection<MySecondObject> getA(){
        return null;
    }

    public ForeignCollection<MyThirdObject> getB(){
        return null;
    }
}

I'm parsing the an empty JSON string:

ObjectMapper mapper = new ObjectMapper();
mapper.readValue("{}", MyObject.class);

On readValue, I get this Exception:

com.fasterxml.jackson.databind.JsonMappingException: Can not find a deserializer for non-concrete Collection type [collection type; class com.j256.ormlite.dao.ForeignCollection, contains [simple type, class com.test.MyThirdObject]]

This happens when I have two get methods in the MyObject class which return a ForeignCollection. Removing one of the get methods results in no exceptions.

I'm actually surprised by the fact that the mapper looks at the get methods, it should just set the fields I indicate.

What is happening here?


回答1:


You need to use the Guava module in your ObjectMapper. Here is the Maven dependency:

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-guava</artifactId>
  <version>{whatever is the latest}</version>
</dependency>

In your code:

ObjectMapper mapper = new ObjectMapper();
// register module with object mapper
mapper.registerModule(new GuavaModule());

You can omit the @JsonDeserialize and @JsonSerialize annotations.

More info here.




回答2:


I've fixed this by converting the ForeignCollection to a List:

private ForeignCollection<MyObject> myObjects;

public List<MyObject> getMyObjects(){
    return new ArrayList<MyObject>(myObjects);
}



回答3:


You may need to define custom deserializer for ForeignCollection; or, if there is known implementation class, use annotation:

@JsonDeserialize(as=ForeignCollectionImpl.class)

to indicate which concrete sub-class to use for that abstract type.



来源:https://stackoverflow.com/questions/14853324/can-not-find-deserialize-for-non-concrete-collection-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!