将平面MapMap到Jackson中的嵌套pojo

relj7zay  于 2022-11-08  发布在  其他
关注(0)|答案(3)|浏览(142)

如何将一个平面MapMap到一个嵌套的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;

}
v6ylcynt

v6ylcynt1#

我看这个办法可以解决这个问题:

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中,这是Jackson所要求的。

eivgtgni

eivgtgni2#

与此同时,Jackson添加了@JsonUnwrapped,lombok添加了@Jacksonized,这将您的开销降至最低:

@Value
@Builder
@Jacksonized
public class Person {

  private String firstName;
  private String lastName;
  @JsonUnwrapped
  private Equipment equipments;
}

注意:@Jacksonized仅在与@Builder结合使用时才有必要。但这会阻止我们使用@NoArgsConstructor

x6yk4ghg

x6yk4ghg3#

我想你把不同职业的属性收集到一个Map上是犯了一个错误。你为什么要这么做?
如果你的json具有相同的结构,那么很容易将json转换为具有嵌套类的对象。在你的例子中,它应该是:
{ "person": { "firstName": "name", "lastName": "name2", "gender": "male", "equipment": { "sword": "s", "shield": "s2" } } }
通过objectMapper.readValue(json, Person.class);可以很容易地将json转换为Person.java

相关问题