使用键值Map对象的Json反序列化

bybem2ql  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(110)

我正在尝试将一个json字符串反序列化为Java对象。下面是我的json字符串。

{
  "header": {
    "transactionId": "12345",
    "application": "testApp"
  },
  "items": {
    "item": [
      {
        "attributes": {
          "attribute": [
            {
              "key": "accountType",
              "value": "TYPE1"
            },
            {
              "key": "accountId",
              "value": "123"
            }
          ]
        }
      },
      {
        "attributes": {
          "attribute": [
            {
              "key": "userType",
              "value": "TYPE2"
            },
            {
              "key": "userId",
              "value": "321"
            }
          ]
        }
      }
    ]
  }
}

我想将这个json反序列化为Java类,如下所示。

public class Response {
    private Header header;
    private List<Object> items;

    //getters and setters
}
public class Header {
    private String transactionId;
    private String application;

    //getters and setters
}
public class Account {
    private String accountType;
    private String accountId;

    //getters and setters
}
public class User {
    private String userType;
    private String userId;

    //getters and setters
}

如何使用Jackson或objectmapper等进行反序列化?主要问题是字段名在属性对象和“key”字段的值中。是否可以使用“key”字段的值在Java对象上找到正确的字段,并使用“value”字段的值设置正确的值?

lymnna71

lymnna711#

一种可能的解决方案是在转换为POJO之前转换JSON结构。
https://github.com/octomix/josson

Josson josson = Josson.fromJsonString(yourJsonString);
JsonNode node = josson.getNode(
    "map(header," +
    "    items: items.item@" +
    "          .attributes.attribute" +
    "          .map(key::value)" +
    "          .mergeObjects()" +
    "   )");
System.out.println(node.toPrettyString());

产出

{
  "header" : {
    "transactionId" : "12345",
    "application" : "testApp"
  },
  "items" : [ {
    "accountType" : "TYPE1",
    "accountId" : "123"
  }, {
    "userType" : "TYPE2",
    "userId" : "321"
  } ]
}

相关问题