我有一个Java类MyPojo,我对从JSON反序列化感兴趣.我已经配置了一个特殊的MixIn类MyPojoDeMixIn来帮助我进行反序列化.MyPojo只有intString个实例变量与适当的getter和setter组合.MyPojoDeMixIn看起来像这样:

public abstract class MyPojoDeMixIn {
  MyPojoDeMixIn(
      @JsonProperty("JsonName1") int prop1,
      @JsonProperty("JsonName2") int prop2,
      @JsonProperty("JsonName3") String prop3) {}
}

In my test client I do the following, but of course it does not work at compile time because there is a JsonMappingException related to a type mismatch.

ObjectMapper m = new ObjectMapper();
m.getDeserializationConfig().addMixInAnnotations(MyPojo.class,MyPojoDeMixIn.class);
try { ArrayList<MyPojo> arrayOfPojo = m.readValue(response, MyPojo.class); }
catch (Exception e) { System.out.println(e) }

我知道我可以通过创建一个只有ArrayList<MyPojo>的"响应"对象来缓解这个问题,但是我必须为我想要返回的每个类型创建这些有点无用的对象.

我也在网上看了JacksonInFiveMinutes,但很难理解Map<A,B>的内容,以及它与我的问题的关系.如果你说不出来的话,我对Java完全陌生,有Obj-C的背景.他们特别提到:

除了绑定到POJO和"简单"类型之外,还有一个

因此,如果要将数据绑定到 map 中,需要使用:

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

我怎么才能直接反序列化到ArrayList呢?

推荐答案

您可以使用TypeReference包装器直接反序列化到列表.示例方法:

public static <T> T fromJSON(final TypeReference<T> type,
      final String jsonPacket) {
   T data = null;

   try {
      data = new ObjectMapper().readValue(jsonPacket, type);
   } catch (Exception e) {
      // Handle the problem
   }
   return data;
}

因此使用:

final String json = "";
Set<POJO> properties = fromJSON(new TypeReference<Set<POJO>>() {}, json);

TypeReference Javadoc

Json相关问答推荐

JOLT将扁平数组内其他字段的两个值相乘

输入请求中不存在null的条件抖动

盒子图显示不正确

写入JSON文件的流

JSON API返回多个数组,需要帮助拼合数据以存储在SQL Server数据库表中

NiFi QueryRecord处理器- Select 可选的JSON属性

在Vega中如何通过滑块改变条形图的宽度

Python 将 struct 化文本转换和筛选为对象

jq :当路径可变时更新 json 内容

如何编写 jolt 规范以将不同的对象转换为数组

数据清理设计不良的 JSON 数据 - 需要有关最佳策略的建议

如何从 json 中获取单个元素?

Powershell 7.2:ConvertFrom-Json - 日期处理

Powershell中等效的JSONPath通配符以 Select 对象中的所有数组

使用 ConvertFrom-Json 后,Powershell 访问 JSON 中的嵌套对象

解析 JSON API 响应

在 JSON API Wordpress 上启用 CORS

TypeError: b'1' 不是 JSON 可序列化的

嵌套 JSON:如何向对象添加(推送)新项目?

你如何在 Arrays of Arrays 上 OPENJSON