【问题标题】:Jackson transforming XML/Bean into Json ArrayJackson 将 XML/Bean 转换为 Json 数组
【发布时间】: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&lt;Description&gt; description; 字段和@XmlElementWrapper
  • 感谢 lexicore,这帮助我解决了这个问题
  • 请发布您的解决方案作为答案。这是一件好事,您将获得一些代表积分作为奖励。 :)

标签: java arrays json jaxb jackson2


【解决方案1】:

我使用来自 lexicore 的指针解决了我的问题,并将我的电话分类更改如下:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Phone", propOrder = {
"description"
 }
@XmlRootElement(name="phone")
public class Phone
          extends PhoneBase
{

@XmlElementWrapper(name = "descriptions")
@JsonProperty(value = "descriptions")
@XmlElement(required = true)
protected List<Description> description;

public List<Description> getDescription() {
if (description == null) {
    description = new ArrayList<Description>();
}
return this.description;
}
}

【讨论】:

    猜你喜欢
    • 2020-03-15
    • 2019-01-04
    • 2016-07-03
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 2012-02-27
    • 2021-12-19
    • 1970-01-01
    相关资源
    最近更新 更多