在jackson中将平面地图映射到嵌套的pojo

时间:2018-02-02 09:52:12

标签: java jackson objectmapper

如何将平面地图映射到嵌套的pojo? 我已经尝试过使用它,但是我在野战剑上得到了一个无法识别的场异常。

Map<String, Object> values = ...;
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(mapper.writeValueAsString(values), Person.class);

我有这个假json:

{
  "firstName": "Arya",
  "lastName": "Stark",
  "gender": "Female",
  "sword" : "Excalibur",
  "shield": "Mighty Shield"
}

一个人类:

@Data
@AllArgsConstructor
public class Person {

 private String firstName;
 private String lastName;
 private Equipment equipments;

}

和设备类:

@Data
@AllArgsConstructor
public class Equipment {

 private String sword;
 private String shield;

}

2 个答案:

答案 0 :(得分:1)

我看到这种方法来解决这个问题:

public class Test {
    public static void main(String[] args) {
        Map<String, Object> values = new HashMap<>();

        values.put("firstName", "Arya");
        values.put("lastName", "Stark");
        values.put("gender", "Female");
        values.put("sword", "Excalibur");
        values.put("shield", "Mighty Shield");
        ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        Person person = mapper.convertValue(values, Person.class);
        person.setEquipments(mapper.convertValue(values, Equipment.class));

        System.out.println(person);

    }
}

当然,它不是一行反序列化,但它有效。结果:

Person(firstName=Arya, lastName=Stark, equipments=Equipment(sword=Excalibur, shield=Mighty Shield))

注意:将@NoArgsConstructor添加到您的POJO中,杰克逊需要它。

答案 1 :(得分:0)

我认为将不同类的属性收集到一个地图时会出错。你为什么这样做?

如果你的json具有相同的结构,那么使用嵌套类很容易将json转换为对象。在你的例子中应该是:

{ "person": { "firstName": "name", "lastName": "name2", "gender": "male", "equipment": { "sword": "s", "shield": "s2" } } }

json可以通过Person.java

轻松转换为objectMapper.readValue(json, Person.class);