0

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.

AMOD MAHAJAN
  • 152
  • 1
  • 10
  • 5
    why in the world you would change the JSON structure of the response... tell those who provided you those API to learn REST and basic API usage... try something like this https://stackoverflow.com/questions/37164399/jackson-desrialize-when-jsonproperty-is-sometimes-array-and-sometimes-a-single-o – Alberto Sinigaglia Aug 21 '21 at 11:06
  • 2
    Just use`List`. If there's a single entry in the JSON, then your `List` will contain a single element. Maybe you have to write a custom deserializer that can distinguish between both cases. – Benjamin M Aug 21 '21 at 11:07

1 Answers1

0

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.

Sam-zhuang
  • 24
  • 5