1

I am using fasterxml.jackson. I am confused about readValue(). Here is my question.

I know jackson deserialize normal JavaBean and Collection in two different ways. For JavaBean, we can pass MyBean.class or new TypeReference<MyBean> to readValue(). For Collections, we must pass new TypeReference<List<MyBean>>. That is because TypeReference saves the type erased by Collection. Am I right? :)

Now I am confused. If MyBean contains a list, then I can still pass MyBean.class and it works. How does jackson do that?

public class MyBean {
    String str;
    List<String> strList;
}
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
zchen
  • 109
  • 2
  • 7
  • The generic type of the strList field is available using reflection. But you can't pass a `List.class` as argument in Java. Only `List.class`. – JB Nizet May 28 '17 at 12:15
  • Maybe this link help you https://stackoverflow.com/a/6349488/6296931 – Coder ACJHP May 28 '17 at 12:16
  • My Question is: I think JSON cannot deserialize List because of type erase. That's why we have to pass TypeReference. But if Java Bean contains List, How can JSON know its generic in Runtime? – zchen May 28 '17 at 13:01

1 Answers1

0

You are passing MyBean.class as the second argument to readValue() and Jackson can get the type from this through reflection. I'd guess Jackson does something like this :

MyBean.class.getDeclaredField("strList").getGenericType();

which will result in a type of java.util.List<java.lang.String>.

Note that you have a non generic class MyBean containing a List<String>. If you had for instance:

class MyGenBean<T> {
    List<T> list;
}

then

MyGenBean.class.getDeclaredField("list").getGenericType();

would return java.util.List<T> and you would need a TypeReference.

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82