如何将平面JSON转换为分层Java类?

编程入门 行业动态 更新时间:2024-10-14 22:17:16
本文介绍了如何将平面JSON转换为分层Java类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要将某些属性设置为子对象的平面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类?

本文发布于:2023-11-30 03:38:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648596.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   平面   JSON   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!