Home > Back-end >  Check whether json attribute is a list or an object in java
Check whether json attribute is a list or an object in java

Time:10-08

I want to convert JSON returned from a service into a java object class. However, I get two types in the same JSON attribute and with that I get the following error Expected begin array but it was begin object. How to test before parsing JSON for my java class? Example of a JSON below:

{
  "name": "ROMEU",
  "age": "24",
  "phone": "xx xxxx xxxx",
  "family": [
    {
      "kinship": "brother",
      "age": "20"
    },
    {
      "kinship": "sister",
      "age": "25"
    }
  ]
}
{
  "name": "ROMEU",
  "age": "24",
  "phone": "xx xxxx xxxx",
  "family": {
    "kinship": "mother",
    "age": "20"
  }
} 

CodePudding user response:

The correct way to fix this is to change the service that returns such a JSON. It makes no sense to either return a List or a single object for the attribute family. This is complexifying what should be simple. Why not returning always a List, that may happen to include a single object?

If this is not possible, then you will need all sorts of Jackson deserialization features to make this work. Even if you are able to do it, it will be ugly I can tell you that. And why? Simply because the service that you are consuming is badly designed.

CodePudding user response:

Assuming you are using Jackson, you can use ACCEPT_SINGLE_VALUE_AS_ARRAY

final ObjectMapper mapper = new ObjectMapper()
    .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

If using GSON, something like

JSONObject response=new JSONObject(res);
if(res.get("family") instanceOf JSONObject) {
    // code for JSONObject
} else if(res.get("family") instanceOf JSONArray) {
    // code for JSONOArray
}
  • Related