简体   繁体   English

如何为Java中字段的动态数据类型创建POJO class?

[英]How to create a POJO class for dynamic data type of field in Java?

I have a dynamic JSON response.我有一个动态的 JSON 响应。

If user has only one address then JSON response will be as below:-如果用户只有一个地址,那么 JSON 响应将如下所示:-

{
  "firstName": "Amod",
  "lastName": "Mahajan",
  "profession": "Software Tester",
  "address": {
    "houseNo": 404,
    "streetName": "Not found",
    "city": "Bengaluru",
    "state": "KA",
    "country": "IN"
  }
}

If user has more than one address then JSON response will be as below:-如果用户有多个地址,则 JSON 响应如下:-

{
  "firstName": "Amod",
  "lastName": "Mahajan",
  "profession": "Software Tester",
  "address": [
    {
       "houseNo": 404,
       "streetName": "Not found",
       "city": "Bengaluru",
       "state": "KA",
       "country": "IN"
   },
   {
  "houseNo": 204,
  "streetName": "No Content",
  "city": "Delhi",
  "state": "DL",
  "country": "IN"
   }
 ]
}

How to create a POJO which can accommodate both?如何创建一个可以容纳两者的 POJO? If I create a POJO for the address part then for first I need to have "Address address" and for the second one "List address".如果我为地址部分创建一个 POJO,那么首先我需要有“地址地址”,第二个需要有“列表地址”。 I want it in single pojo which can accommodate both dynamically.我想要它在单个 pojo 中,它可以动态地容纳两者。

I think that the value corresponding to the key “address”'s type should be always declared with type array , although it only has one element.我认为对应于键“address”的类型的值应该总是声明为array类型,尽管它只有一个元素。 If you do not want to change the JSON structure, the POJO class declaration is the following code.如果不想改变JSON结构,POJO class声明就是下面的代码。

public class Person {
    // omit other fields and getter and setter.
    List<Address> addressInfo;
}

As we can see, we can use List to denote one or more address information, you can also use Address[] to denote it.可以看到,我们可以用List来表示一个或多个地址信息,也可以用Address[]来表示。

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

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