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

前端之家收集整理的这篇文章主要介绍了杰克逊嵌入式Java对象的反序列化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我必须反序列化以下json使用杰克逊图书馆进入客户类
{
   "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对象?

解决方法

您可以在客户类的“地址”字段中添加一个 @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'}}

猜你在找的Java相关文章