Json Java 多个 POJO 的数据绑定

Json Java Data Binding for multiple POJOs

是否可以使用 ObjectMapper 解析包含多个对象的 JSON?例如

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

我能否在一个映射器 运行 中从该文件中获取对象 Employee、Department、Company,例如:

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

还是不可能?

创建一个包含您要查找的 3 个对象的父对象,并将它们读入该单个对象,然后使用该对象访问您的数据。

如果我们考虑

的情况

reading numerous objects in one file separately

,无需创建专用的包装器 POJO,这也是可以实现的,前提是您具有 JSON 中的每个根级键应映射到哪个目标对象类型的信息。

此信息可以表示为Map:

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

反序列化必须分两步完成。第一个是把原来的JSON改成Map<String, Object>:

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

第二步是将此映射的键与目标类型匹配并将值转换为对象:

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

objects 列表现在包含

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