Jackson and the generic link type

I want to use the Jackson JSON library for a generic method as follows:

public MyRequest<T> tester() { TypeReference<MyWrapper<T>> typeRef = new TypeReference<MyWrapper<T>>(); MyWrapper<T> requestWrapper = (MyWrapper<T>) JsonConverter.fromJson(jsonRequest, typeRef); return requestWrapper.getRequest(); } 

...

 public class MyWrapper<T> { private MyRequest<T> request; public MyRequest<T> getRequest() { return request; } public void setRequest(MyRequest<T> request) { this.request = request; } } public class MyRequest{ private List<T> myobjects; public void setMyObjects(List<T> ets) { this.myobjects = ets; } @NotNull @JsonIgnore public T getMyObject() { return myobjects.get(0); } } 

Now the problem is that when I call getMyObject (), which is inside the request object, Jackson returns the nested user object as a LinkedHashMap. Is there a way to indicate that the object T should be returned? For example: if I sent an object of type Customer, then Customer should be returned from this list ?.

Thank you

+84
java json generics jackson
Jul 27 2018-11-14T00:
source share
2 answers

This is a well-known issue with Java type erasure: T is just a type variable, and you should specify the actual class, usually as an argument to the class. Without such information, the best that can be done is to use boundaries; and a simple T is about the same as a "T extends Object". Jackson will then link the JSON objects as Maps.

In this case, the tester method should have access to the class, and you can build

 JavaType type = mapper.getTypeFactory(). constructCollectionType(List.class, Foo.class) 

and then

 List<Foo> list = mapper.readValue(new File("input.json"), type); 
+149
Jul 27 '11 at 22:51
source share

'JavaType' works !! I tried to untie (deserialize) the list in json String in ArrayList java Objects and struggled to find a solution ever since. Below is the code that finally gave me the solution. The code:

 JsonMarshallerUnmarshaller<T> { T targetClass; public ArrayList<T> unmarshal(String jsonString) { ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector introspector = new JacksonAnnotationIntrospector(); mapper.getDeserializationConfig() .withAnnotationIntrospector(introspector); mapper.getSerializationConfig() .withAnnotationIntrospector(introspector); JavaType type = mapper.getTypeFactory(). constructCollectionType( ArrayList.class, targetclass.getClass()); try { Class c1 = this.targetclass.getClass(); Class c2 = this.targetclass1.getClass(); ArrayList<T> temp = (ArrayList<T>) mapper.readValue(jsonString, type); return temp ; } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null ; } } 
+6
Mar 05 '13 at 17:07
source share



All Articles