我需要将某些属性设置为子对象的平面JSON对象反序列化为Java对象.
I need to deserialize a flat JSON object to a Java object with some properties set to child object.
{ "name": "abcd", "addressLine1": "123", "addressLine2": "1111" }Class Student { String name; Address address; } Class Address { String line1; String line2; }
如何使用Jackson将我的JSON反序列化为Student对象? 我无法映射addressLine1 to Student.Address.line1 和addressLine2 to Student.Address.line2
How do I deserialize my JSON using Jackson into a Student object? I am not able to map addressLine1 to Student.Address.line1 and addressLine2 to Student.Address.line2
推荐答案您可以通过以下方式定义数据类:
You can define your data classes this way:
public static class Student { String name; @JsonUnwrapped Address address; } public static class Address { @JsonProperty("addressLine1") String line1; @JsonProperty("addressLine2") String line2; }然后,您可以按常规方式使用Objectmapper-无需任何其他技巧或解决方法:
Then you can use the Objectmapper in the usual way - without any additional magic or workaround :
Student student = mapper.readValue(json, Student.class);如果传入的json字符串确实采用您提供的格式(不带引号),则还要添加:
If your incoming json string is indeed in the format you provided (without quotes) then also add:
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);更多推荐
如何将平面JSON转换为分层Java类?
发布评论