杰克逊嵌入式Java对象的反序列化

时间:2016-02-26 10:00:44

标签: java json jackson deserialization

我必须使用Jackson库将json反序列化为Customer class

{
   "code":"C001",
   "city": "Pune",
   "street": "ABC Road"
}

和类作为

class Address{
    String city;
    String street;
}

class Customer{
    String code;
    Address address;
}

我在堆栈上发现了类似的问题 Java jackson embedded object deserialization

但答案不适用于我的情况。另外我只想使用杰克逊图书馆。

如何将此json映射到Customer对象?

5 个答案:

答案 0 :(得分:6)

您可以在客户类的Address字段中添加@JsonUnwrapped注释。这是一个例子:

public class JacksonValue {
    final static String JSON = "{\n"
            +"   \"code\":\"C001\",\n"
            +"   \"city\": \"Pune\",\n"
            +"   \"street\": \"ABC Road\"\n"
            +"}";

    static class Address {
        public String city;
        public String street;

        @Override
        public String toString() {
            return "Address{" +
                    "city='" + city + '\'' +
                    ", street='" + street + '\'' +
                    '}';
        }
    }

    static class Customer {
        public String code;
        @JsonUnwrapped
        public Address address;

        @Override
        public String toString() {
            return "Customer{" +
                    "code='" + code + '\'' +
                    ", address=" + address +
                    '}';
        }
    }


    public static void main(String[] args) throws IOException {
        final ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.readValue(JSON, Customer.class));
    }
}

输出:

 Customer{code='C001', address=Address{city='Pune', street='ABC Road'}}

答案 1 :(得分:2)

您需要的是自定义反序列化器。 Jackson How-To: Custom Deserializers

对于您的用例,它可能是这样的:

class CustomerDeserializer extends JsonDeserializer<Customer>
{
  public Customer deserialize(JsonParser p, DeserializationContext ctxt) 
                                        throws IOException, JsonProcessingException
  {
    JsonNode node = p.getCodec().readTree(p);
    String code = node.get("code").asText();
    String city = node.get("city").asText();
    String street = node.get("street").asText();
    Address adr = new Address(city, street);
    return new Customer(code, adr);
  }
}

答案 2 :(得分:1)

客户的JSON对象应如下所示:

{
   "code":"C001",
   "address":{
        "city": "Pune",
        "street": "ABC Road"
   } 
}

答案 3 :(得分:1)

如果没有一些额外的转换,这个json结构就不能映射到两个类。编写一个将从json中获取所有三个字段的类CustomerAddress,然后在其中创建Address getAddress()Customer getCustomer(),或者转换json以将地址信息嵌套在customer字段中,如下所示: @eztam。

public CustomerAddress {
  private String code;
  private String city;
  private String street;

  public Address getAddress() {
    return new Address(city, street);
  }

  public Address getCustomer() {
    return new Customer(code, this.getAddress());
  }
}

答案 4 :(得分:1)

试试这个!!!

{  
       "code":"customer1",
       "address":{  
          "type":"nested",
          "properties":{  
             "city":"Hyderabad",
             "street":"1000ftRoad"
          }
       }
    }