Using Jackson ObjectMapper with Generics to POJO instead of LinkedHashMap

a 夏天 提交于 2019-12-10 12:57:09

问题


Using Jersey I'm defining a service like:

@Path("/studentIds")
public void writeList(JsonArray<Long> studentIds){
 //iterate over studentIds and save them
}

Where JsonArray is:

public class JsonArray<T> extends ArrayList<T> {  
    public JsonArray(String v) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper(new MappingJsonFactory());
        TypeReference<ArrayList<T>> typeRef = new TypeReference<ArrayList<T>>() {};
        ArrayList<T> list = objectMapper.readValue(v, typeRef);
        for (T x : list) {
            this.add((T) x);
        }
    }
}

This works just fine, but when I do something more complicated:

@Path("/studentIds")
public void writeList(JsonArray<TypeIdentifier> studentIds){
 //iterate over studentIds and save them by type
}

Where the Bean is a simple POJO such as

public class TypeIdentifier {
    private String type;
    private Long id;
//getters/setters 
}

The whole thing breaks horribly. It converts everything to LinkedHashMap instead of the actual object. I can get it to work if I manually create a class like:

public class JsonArrayTypeIdentifier extends ArrayList<TypeIdentifier> { 
    public JsonArrayTypeIdentifier(String v) throws IOException  {
        ObjectMapper objectMapper = new ObjectMapper(new MappingJsonFactory());
        TypeReference<ArrayList<TypeIdentifier>> typeRef = new TypeReference<ArrayList<TypeIdentifier>>(){};
        ArrayList<TypeIdentifier> list = objectMapper.readValue(v, typeRef);
        for(TypeIdentifier x : list){
            this.add((TypeIdentifier) x);
        }
    }
 }

But I'm trying to keep this nice and generic without adding extra classes all over. Any leads on why this is happening with the generic version only?


回答1:


First of all, it works with Longs because that is sort of native type, and as such default binding for JSON integral numbers.

But as to why generic type information is not properly passed: this is most likely due to problems with the way JAX-RS API passes type to MessageBodyReaders and MessageBodyWriters -- passing java.lang.reflect.Type is not (unfortunately!) enough to pass actual generic declarations (for more info on this, read this blog entry).

One easy work-around is to create helper types like:

class MyTypeIdentifierArray extends JsonArray<TypeIdentifier> { }

and use that type -- things will "just work", since super-type generic information is always retained.



来源:https://stackoverflow.com/questions/8903863/using-jackson-objectmapper-with-generics-to-pojo-instead-of-linkedhashmap

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