Search code examples
javajsonjackson-databind

JSON Objects with Field that is sometimes an Array


Problem:Sometimes an Access Request Target is a Single Target, Sometimes it is an array

Question: How can I make Jackson deserialize to either a Single Target or an Array depending on what is found?

Single Target JSON

                                    "access_request": {
                                    "targets": {
                                        "target": {
                                            "@type": "ANY",
                                            "id": 1189118
                                        }
                                    }
                                } 

Array of Target JSON

                                    "access_request": {
                                    "targets": {
                                        "target": [
                                            {
                                                "@type": "Object",
                                                "id": 1189167,
                                                "object_name": "OUTSIDE",
                                                "object_type": "acl",
                                                "object_details": "2.2.2.2",
                                                "management_id": 29,
                                                "management_name": "ace2"
                                            },
                                            {
                                                "@type": "Object",
                                                "id": 1189168,
                                                "object_name": "ONRAMP",
                                                "object_type": "acl",
                                                "object_details": "1.1.1.1",
                                                "management_id": 29,
                                                "management_name": "ace1"
                                            }
                                        ]
                                    } 
                                }

'Target' POJO:

@JsonPropertyOrder({
"target"

}) @Generated("jsonschema2pojo") public class Targets implements Serializable {

@JsonProperty("target")
private Target target = new Target();//How can I make Jackson deserialize to either a Single Target or an Array<Target> depending on what is found?
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
.
.//Getters, Setters
.

}


Solution

  • Use a single field of type List, and activate the feature ACCEPT_SINGLE_VALUE_AS_ARRAY

    YourTargetClass result = mapper.reader(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
                             .forType(YourTargetClass.class)
                             .readValue(json);