简体   繁体   English

如何将多个 JSON 响应映射到单个 Java POJO?

[英]How to map multiple JSON responses to a single Java POJO?

Need to map multiple types of JSON responses to a single POJO so that I can compare the different objects to provide insight about the differences.需要将多种类型的 JSON 响应映射到单个 POJO,以便我可以比较不同的对象以提供有关差异的见解。

I had tried mapping the first response to the POJO and parsed the second response to populate the defined POJO:我曾尝试将第一个响应映射到 POJO 并解析第二个响应以填充定义的 POJO:

    class XXX {
        @JsonProperty("accountHolder")
        private String accountHolder;
        @JsonProperty("routingNumber")
        private String routingNumber;
        @JsonProperty("balance")
        private List<Balance> balance;
        @JsonProperty("accountName")
        private String accountName;
        @JsonProperty("bankTransferCodeType")
        private String bankTransferCodeType;
        @JsonProperty("individualInformation")
        private IndividualInformation individualInformation;
        @JsonProperty("acctType")
        private String acctType;
        @JsonProperty("transactionList")
        private TransactionList transactionList;
        @JsonProperty("accountNumber")
        private String accountNumber;
        @JsonProperty("uniqueId")
        private String uniqueId;
        @JsonProperty("bankNetID")
        private String bankNetID;
        @JsonIgnore
        private Map<String, Object> additionalProperties = new HashMap<String, Object>();
    }

First response:第一反应:


[
    {
        "ACCOUNT_NAME": "",
        "ACCOUNT_NUMBER": "",
        "AVAILABLE_BALANCE": null,
        "CURRENT_BALANCE": "",
        "FULL_ACCOUNT_NUMBER": null,
    }
]

Second response:第二个回应:

"bankAccount": [
      {
        "accountName": "",
        "accountNumber": "",
        "routingNumber": "",
        "fullAccountNumber": "",
        "bankTransferCodeType": "",
        "acctType": "",
        "transactionList": {
          "transaction": [
            {
              "amount": {
                "curCode": "",
                "content": ""
              }
          ],
          "oldestTxnDate": ""
        },
        "uniqueId":
      }
}

Expecting a generic way to map the different structured JSON entities to single POJO.期待一种将不同结构化 JSON 实体映射到单个 POJO 的通用方法。

It doesn't seems to have any generic way.它似乎没有任何通用的方式。 But you can do this:但是你可以这样做:

  • Create multiple domain classes for each response type为每个响应类型创建多个域类
  • Create a single standard domain class创建单个标准域类
  • Create mapper for each response class to map that to standard domain class.为每个响应类创建映射器以将其映射到标准域类。 You can use MapStruct reference here您可以在此处使用 MapStruct参考

How to map multiple JSON responses to a single Java POJO?如何将多个 JSON 响应映射到单个 Java POJO?

As both responses seem to be completely different from each other, with nothing in common, I would refrain from attempting to use a single class for reading both responses.由于两个响应似乎彼此完全不同,没有任何共同之处,因此我不会尝试使用单个类来读取两个响应。

Expecting a generic way to map the different structured JSONs to single POJO.期待一种将不同结构的 JSON 映射到单个 POJO 的通用方法。

  1. You could parse both responses as a Map<String, Object> and then map the values to a common class.您可以将两个响应解析为Map<String, Object> ,然后将值映射到一个公共类。

  2. You could create separated classes for mapping each response.您可以创建单独的类来映射每个响应。 It will allow you to decouple them and evolve them as you need.它将允许您将它们解耦并根据需要发展它们 You also can use use mapping frameworks such as MapStruct for reducing the boilerplate code when mapping from one object to another.在从一个对象映射到另一个对象时,您还可以使用映射框架(例如MapStruct)来减少样板代码。

I would suggest using Jackson Json Views.我建议使用 Jackson Json Views。 Here is an example for the same :这是相同的示例:

Example例子

public class Views {

    public class Global {
    }

    public class Internal extends Global {
    }
}

class XXX {

    @JsonView(Views.Global.class)
    @JsonProperty("accountHolder")
    private String accountHolder;

    @JsonView(Views.Internal.class)
    @JsonProperty("routingNumber")
    private String routingNumber;

}

Hope it helps.希望能帮助到你。

What I did is I created a MyResponse model containing basically all response fields from the JSON response you expect to get.我所做的是创建了一个 MyResponse 模型,该模型基本上包含您期望获得的 JSON 响应中的所有响应字段。 MyResponse has c-tor or receiving these fields or setters allowing setting them. MyResponse 具有 c-tor 或接收这些字段或设置器,允许设置它们。

Then I created some kind of service class MyService that can issue multiple requests and gets responses back.然后我创建了某种服务类 MyService ,它可以发出多个请求并返回响应。

Then you just do something like this in some kind of manager class or whatever you call it:然后,您只需在某种经理课程或任何您称之为的课程中做这样的事情:

MyService mySer = new MyService();

MyResponse myRes = new MyResponse(
  mySer.getDetails(),
  mySer.getPicture(),
  mySer.getSomethingElse()
);

These calls (getDetails, getPicture...) send requests to end point and return responses which are then just mapped into the the fields of MyResponse class constructor.这些调用(getDetails、getPicture...)将请求发送到端点并返回响应,然后将响应映射到 MyResponse 类构造函数的字段中。 This happens by the framework so MyResponse has annotations @XmlRootElement and @XmlAccessorType of type FIELD to ensure that happens.这是由框架发生的,因此 MyResponse 具有类型为 FIELD 的 @XmlRootElement 和 @XmlAccessorType 注释以确保发生这种情况。 If for whatever reason, you dont want to create response containing result of getPicture for example, you just assign null to that imput parameter.如果出于某种原因,您不想创建包含 getPicture 结果的响应,例如,您只需将 null 分配给该输入参数。

I suggest to use @JsonProperty("") and @JsonAlias("").我建议使用@JsonProperty("") 和@JsonAlias("")。

 class XXX {
    @JsonAlias("accountName")
    @JsonProperty("ACCOUNT_NAME")
    private String name;

    @JsonAlias("routingNumber")
    @JsonProperty("ROUTING_NUMBER")
    private String routing;}

I hope it helps.我希望它有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM