json java arraylist_java – 使用Jackson将JSON解析为ArrayList

我有一个Java类MyPojo,我有兴趣反序列化从JSON。我已经配置了一个特殊的MixIn类,MyPojoDeMixIn,以帮助我反序列化。 MyPojo只有int和String实例变量与正确的getter和setter组合。 MyPojoDeMixIn看起来像这样:

public abstract class MyPojoDeMixIn {

MyPojoDeMixIn(

@JsonProperty("JsonName1") int prop1,

@JsonProperty("JsonName2") int prop2,

@JsonProperty("JsonName3") String prop3) {}

}

在我的测试客户端我做以下,但当然它不工作在编译时,因为有一个类型不匹配的JsonMappingException。

ObjectMapper m = new ObjectMapper();

m.getDeserializationConfig().addMixInAnnotations(MyPojo.class,MyPojoDeMixIn.class);

try { ArrayList arrayOfPojo = m.readValue(response, MyPojo.class); }

catch (Exception e) { System.out.println(e) }

我知道,我可以通过创建一个“响应”对象缓解这个问题,只有一个ArrayList< MyPojo>在它,但然后我将不得不创建这些有点无用的对象为我想要返回的每一个类型。

我也在线看着JacksonInFiveMinutes,但有一个可怕的时间了解地图< A,B&以及它如何与我的问题有关。如果你不能告诉,我是全新的Java和来自Obj-C背景。他们特别提到:

In addition to binding to POJOs and “simple” types, there is one

additional variant: that of binding to generic (typed) containers.

This case requires special handling due to so-called Type Erasure

(used by Java to implement generics in somewhat backwards compatible

way), which prevents you from using something like

Collection.class (which does not compile).

So if you want to bind data into a Map you will need to use:

Map result = mapper.readValue(src, new TypeReference>() { });

如何直接反序列化为ArrayList?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值