3

I am needing to parse JSON data coming in from an outside source. The problem is sometimes and array of data is sent in and sometimes it come in as a single object, but the array and the single object have the same name.

{
  "OuterObject": {
    "Names":[
      {
      "name": "John Doe"
      },
      {
      "name": "William Watson"
      }
    ]
  }
}

But when the JSON array has only one element, it looks like this:

{
"OuterObject": {
    "Names": {
    "name": "John Doe"
    }
  }
}

My application needs to be able to handle either one of these, but not both at the same time.

This is what my Json parsed class looks like:

@JsonRootName("OuterObject")
public class OuterObject {

    @JsonProperty("Names")
    private Names names;
    @JsonProperty("Names")
    private List<Names> namesList;

    public Names getNames() {
        return names;
    }
    public void setNames(Names names) {
        this.names = names;
    }
    public List<Names> getNamesList() {
        return namesList;
    }
    public void setNamesList(List<Names> namesList) {
        this.namesList = namesList;
    }

}

However, it doesn't look like it will work to have the same json property name for both the list and the single object. It also doesn't appear to just use an array and have the single json object parse into the list. Does anyone know of any ways that my application can handle both json arrays and single json objects when the arrays and the objects have the same name?

RLeyva
  • 77
  • 2
  • 8

3 Answers3

4

You just need to use a single field of type List<Names>, and activate the feature ACCEPT_SINGLE_VALUE_AS_ARRAY

YourClass result = mapper.reader(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
                         .forType(YourClass.class)
                         .readValue(json);
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

I have used following method for convert JSONArray, if it is only one JSONObject.

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

private JSONArray getJSONArray(JSONObject json, String field) {
        JSONArray array;
        if(json.get(field) instanceof JSONObject){
            array = new JSONArray();
            array.add(json.get(field));
        }else{
            array = json.getJSONArray(field);
        }
        return array;
    }
Thusitha Indunil
  • 832
  • 1
  • 8
  • 22
-1

Convert your json to Map then use your code to get the desired result.

ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.convertValue(json, Map.class);

or better

Map<String, Object> map = mapper.convertValue(json, new TypeReference<Map<String, Object>>() {});
Ashish Lohia
  • 269
  • 1
  • 12