杰克逊:将json的某些字段映射到类的内部字段

时间:2017-01-31 13:00:25

标签: java json jackson

我想将json的某些字段映射到类的内部字段。 e.g

{
 values:[{
 "name":"Abc",
 "age":18,
 "street":"test", 
 "postalcoad":"1231412"
},
 {
  "name":"ccvb",
 "age":20,
 "street":"test2", 
 "postalcoad":"123"
  }
]}

关注我的java课程

@JsonIgnoreProperties(ignoreUnknown = true)
public class Customer{
   @JsonProperty("name")
   private string name;

   @JsonProperty("age")
   private int age;

   private Address address;
}

@JsonIgnoreProperties(ignoreUnknown = true)
public class Address{
   @JsonProperty("street")
   private string street;

   @JsonProperty("postalcode")
   private string postalcode;
}


ObjectMapper mapper = new ObjectMapper();
Customer[] c = mapper.readValue(mapper.readTree(json).get("values").toString(), Customer[].class);

它返回没有地址的Customer对象。知道如何从这个json创建Address对象。

2 个答案:

答案 0 :(得分:3)

其中一个选项是使用Date | FiscalDate | YearMonth -----------|------------|---------- 08/01/2010 | 11/01/2010 | 201008 09/01/2010 | 12/01/2010 | 201009 10/01/2010 | 01/01/2011 | 201010 11/01/2010 | 02/01/2011 | 201011 12/01/2010 | 03/01/2011 | 201012 01/01/2011 | 04/01/2011 | 201101 注释:

@JsonCreator

第二个选项是创建自定义反序列化器,并使用 @JsonCreator public Customer( @JsonProperty("name") String name, @JsonProperty("age") int age, @JsonProperty("street") String street, @JsonProperty("postalcode") String postalcode ) { this.name = name; this.age = age; this.address = new Address(); this.address.street = street; this.address.postalcode = postalcode; } 注释将您的类与反序列化器绑定

@JsonDeserialize

作为第三个选项,您可以使用@JsonDeserialize(using = CustomerDeserializer.class) public static class Customer{ .... } public class CustomerDeserializer extends StdDeserializer<Customer> { public CustomerDeserializer() { super(Customer.class); } @Override public Customer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { Customer customer = new Customer(); JsonNode treeNode = p.readValueAsTree(); if (treeNode == null) { return null; } customer.setName(treeNode.get("name").asText()); customer.setAge(treeNode.get("age").asInt()); Address address = new Address(); address.setStreet(treeNode.get("street").asText()); address.setPostalcode(treeNode.get("postalcode").asText()); customer.setAddress(address); return customer; } } 进行某种后期构建处理:

@JsonAnySetter

答案 1 :(得分:1)

我会创建一个自定义反序列化器,并在其中调用Customer的默认反序列化器,然后调用Address的默认反序列化器。然后将地址添加到客户对象。这样他们都看同一个json,但你得到两个不同的对象,你可以按照你想要的方式连接它们。

要从自定义deseriazlier调用标准反序列化器,请参阅以下答案:How do I call the default deserializer from a custom deserializer in Jackson