[英]How JSON deserialize Array?
I am using fasterxml.jackson. 我正在使用fasterxml.jackson。 I am confused about
readValue()
. 我对
readValue()
感到困惑。 Here is my question. 这是我的问题。
I know jackson deserialize normal JavaBean and Collection in two different ways. 我知道jackson以两种不同的方式反序列化普通的JavaBean和Collection。 For JavaBean, we can pass
MyBean.class
or new TypeReference<MyBean>
to readValue()
. 对于JavaBean,我们可以将
MyBean.class
或new TypeReference<MyBean>
传递给readValue()
。 For Collections, we must pass new TypeReference<List<MyBean>>
. 对于集合,我们必须传递
new TypeReference<List<MyBean>>
。 That is because TypeReference
saves the type erased by Collection. 这是因为
TypeReference
保存了Collection删除的类型。 Am I right? 我对吗? :)
:)
Now I am confused. 现在我很困惑。 If
MyBean
contains a list, then I can still pass MyBean.class
and it works. 如果
MyBean
包含一个列表,那么我仍然可以传递MyBean.class
并且它可以工作。 How does jackson do that? 杰克逊是怎么做到的?
public class MyBean {
String str;
List<String> strList;
}
You are passing MyBean.class
as the second argument to readValue()
and Jackson can get the type from this through reflection. 您正在将
MyBean.class
作为readValue()
的第二个参数传递,而Jackson可以通过反射从中获取类型。 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>
. 这将导致一种
java.util.List<java.lang.String>
。
Note that you have a non generic class MyBean
containing a List<String>
. 请注意,您有一个包含
List<String>
的非泛型class MyBean
。 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
. 将返回
java.util.List<T>
,你需要一个TypeReference
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.