【发布时间】:2018-12-08 07:46:06
【问题描述】:
(请注意,我仅提供 sn-ps 代码来解释我的情况,这些不是完整的对象) 我正在使用杰克逊2.8.2。我有以下格式的 xml:
<descriptions>
<description description1="1" description1Text="text1" />
<description description1="6" description1Text="text2" description2="19" description2Text="Board Member (BRD)" />
</descriptions>
我使用 JAXB 将这个 XML 转换为 Java POJO,如下所示:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Phone", propOrder = {
"descriptions"
}
@XmlRootElement(name="phone")
public class Phone extends PhoneBase {
protected Descriptions descriptions;
getter()
setter();
}
描述类如下:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Descriptions", propOrder = {
"description"
})
public class Descriptions {
@XmlElement(required = true)
protected List<Description> description;
public List<Description> getDescription() {
if (description == null) {
description = new ArrayList<Description>();
}
return this.description;
}
}
当我使用 Jackson 将以上 POJO 转换为 JSON 时,我得到以下结果:
{
"descriptions": {
"description": [{
"description1": "1",
"description1_text": "text1"
}, {
"description1": "6",
"description1_text": "text2",
"description2": "19",
"description2_text": "Board Member (BRD)"
}
] } }
虽然我希望它如下:
{
"descriptions": [{
"description1": "1",
"description1_text": "text1"
}, {
"description1": "6",
"description1_text": "text2",
"description2": "19",
"description2_text": "Board Member (BRD)"
}
]}
请注意我不希望父节点但子节点表示为 JSON 数组以及此键的名称是父节点的名称。 有人可以建议我如何实现这一目标吗?
谢谢
【问题讨论】:
-
直接在
Phone类中尝试private List<Description> description;字段和@XmlElementWrapper。 -
感谢 lexicore,这帮助我解决了这个问题
-
请发布您的解决方案作为答案。这是一件好事,您将获得一些代表积分作为奖励。 :)
标签: java arrays json jaxb jackson2