简体   繁体   中英

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

I have a dynamic JSON response.

If user has only one address then JSON response will be as below:-

{
  "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:-

{
  "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? 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". I want it in single pojo which can accommodate both dynamically.

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. If you do not want to change the JSON structure, the POJO class declaration is the following code.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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