Ewgenij Sokolovski
Ewgenij Sokolovski

Reputation: 967

Json Java Data Binding for multiple POJOs

Is it possible to parse a JSON containing multiple Objects with the ObjectMapper? For example

{
  "employee": {
    "name": "John",
    "surname": "Smith",
    "age": 30,
    "department": "sales"
  },
  "department": {
    "name": "sales",
    "company": "abcd",
    "lead": "Mr Harrison"
  },
  "company": {
    "name": "abcd",
    "location": "New York"
  }
}

Can I get the objects Employee, Department, Company out of that file in one single mapper run, something like:

ObjectMapper mapper = new ObjectMapper(); List of Objects = mapper.readValue(...)

Or is it not possible?

Upvotes: 0

Views: 905

Answers (2)

Antot
Antot

Reputation: 3964

If we consider the case of

reading numerous objects in one file separately

, without creating a dedicated wrapper POJO, this is also possible to achieve, provided that you have the information to which target object type should be mapped each of the root-level keys in the JSON.

This information can be represented in a Map:

Map<String, Class<?>> targetTypes = new HashMap<>();
targetTypes.put("employee", Employee.class);
targetTypes.put("department", Department.class);
targetTypes.put("company", Company.class);

The deserialization will have to be done in two steps. The first one is to transform the original JSON into a Map<String, Object>:

String json = ... // the JSON
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> parsed = mapper.readValue(json, Map.class);

The second step is to match the keys of this map with the target types and transform the values into objects:

List<Object> objects = parsed.entrySet().stream().map(
    (entry) -> {
      Class<?> targetClass = targetTypes.get(entry.getKey());
      return mapper.convertValue(entry.getValue(), targetClass);
    }
).collect(Collectors.toList());

The objects list now contains

[
 Employee(name=John, surname=Smith, age=30, department=sales), 
 Department(name=sales, company=abcd, lead=Mr Harrison), 
 Company(name=abcd, location=New York)
]

Upvotes: 0

Adam Pine
Adam Pine

Reputation: 387

Make a parent object that contains the 3 objects you are looking for, and read them into that single object, then use that object to access your data.

Upvotes: 1

Related Questions