jackson 使用具有动态键的对象的嵌套数组反序列化json字符串

egdjgwm8  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(152)

给定JSON字符串,我需要将其转换为名为TransactionInfoPOJO

JSON字符串

{
  "transactionId": "EFODKKXHE003",
  "isSettled": false,
  "transactionProperties": [
    {
      "key1": "Value1"
    },
    {
      "key2": "Value2"
    },
    {
      "key3": "Value3"
    }
  ]
}

波约

class TransactionInfo {
   String transactionId;
   Boolean isSettled;
   Map<String,String> transactionProperties;
}

附加注解(来自备注)

在反序列化之后,我想访问transactionPropertiesMap中的不同键。如果将其转换为List<Map<String,String>>,则会变得复杂。仅供参考,这些键保证是唯一的,因此最后,我需要一个单一的平面Map。另外,我不需要将TransactionInfo序列化回JSON
"我的努力"

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.readValue(jsonString, TransactionInfo.class);

但我得到了一个例外,如下所示:
无法从数组值(标记JsonToken.START_ARRAY)反序列化java.util.LinkedHashMap<java.lang.String,java.lang.Object>类型的值
有谁能指导我如何正确地做这件事吗?任何帮助都非常感谢。

编辑

我已经浏览了以下帖子,但似乎没有一个与我的用例匹配

pnwntuvh

pnwntuvh1#

保证是唯一的,所以最后,我只需要一个平面Map。另外,我不需要将TransactionInfo序列化回JSON。

由于所有键都是唯一的,并且您不关心将此POJO序列化回JSON,因此可以将Map列表转换为构造函数中的 map

public class TransactionInfo {
    String transactionId;
    Boolean isSettled;
    Map<String, String> transactionProperties;

    public TransactionInfo(String transactionId, Boolean isSettled, Map<String, String> transactionProperties) {
        this.transactionId = transactionId;
        this.isSettled = isSettled;
        this.transactionProperties = transactionProperties;
    }

    public TransactionInfo(
        @JsonProperty("transactionId") String transactionId,
        @JsonProperty("isSettled") Boolean isSettled,
        @JsonProperty("transactionProperties") List<Map<String, String>> transactionPropertiesList) {

        this.transactionId = transactionId;
        this.isSettled = isSettled;
        this.transactionProperties = transactionPropertiesList.stream()
            .flatMap(map -> map.entrySet().stream())
            .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue
            ));
    }
}

main()的代码片段:

String json = """
            {
               "transactionId": "EFODKKXHE003",
               "isSettled": false,
               "transactionProperties": [
                 {
                   "key1": "Value1"
                 },
                 {
                   "key2": "Value2"
                 },
                 {
                   "key3": "Value3"
                 }
               ]
             }""";

ObjectMapper mapper = new ObjectMapper();
TransactionInfo transactionInfo = mapper.readValue(json, TransactionInfo.class);
System.out.println(transactionInfo);
  • 输出:*
TransactionInfo{transactionId='EFODKKXHE003', isSettled=false, transactionProperties={key1=Value1, key2=Value2, key3=Value3}}
jdg4fx2g

jdg4fx2g2#

一种选择是将transactionProperties字段的类型更改为List<ObjectNode>,然后遍历列表,并对每个元素使用其fields()方法来检索其成员

相关问题