borgmater
borgmater

Reputation: 706

Mapping JSON with multiple entries to an array

I have a JSON file with multiple entries that have same attribute names, but different attribute values, such as:

{
  "name" : { "first" : "A", "last" : "B" },
  "gender" : "MALE",
  "married" : false,
  "noOfChildren" : 2
},
{
  "name" : { "first" : "C", "last" : "D" },
  "gender" : "FEMALE",
  "married" : true,
  "noOfChildren" : 1
}

The class that it should be mapped is:

public class Human {

private Name name;
private String gender;
private int age;

<getter, setters etc>

}

EDIT: Service code is :

List<Human> humans = null;
ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

try {

    humans= objectMapper.readValue(json, new TypeReference<List<Human>>(){});

} catch (IOException e) {
    e.printStackTrace();
}

JSON is parsed from HTTP entity and with correct format and now I added the annotation ass suggested in the answers.

As you can see, they have some attributes in common, but differ in others, and I would like to map those common fields. Is it possible to map the JSON this way ? I have tried mapping JSON to a collection/list/array of JsonNodes, but I keep getting erros about deserialization, while mapping only one instance of JSON entry works just fine. Is there another way of doing this ?

Upvotes: 0

Views: 650

Answers (2)

Sachin Gupta
Sachin Gupta

Reputation: 8358

use

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

while deserializing json to POJO class.

The JSON you have provide in question will give following error, as it is not a valid one.

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

Valid Json would be like this:

[
  {
    "name": {
      "first": "A",
      "last": "B"
    },
    "gender": "MALE",
    "married": false,
    "noOfChildren": 2
  },
  {
    "name": {
      "first": "C",
      "last": "D"
    },
    "gender": "FEMALE",
    "married": true,
    "noOfChildren": 1
  }
]

Upvotes: 1

Dmitry Gorkovets
Dmitry Gorkovets

Reputation: 2276

Use

@JsonIgnoreProperties(ignoreUnknown = true)
public class Human {
    private Name name;
    private String gender;
    // getters, settets, default constructor
}

Or if you are using Lombok then it will be

@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Human {
    private Name name;
    private String gender;
}

Upvotes: 1

Related Questions