Jackson将XML / Bean转换为Json Array

时间:2018-06-29 07:13:42

标签: java arrays json jaxb jackson2

(请注意,我仅提供代码片段来说明我的情况,而这些不是完整的对象) 我正在使用Jackson2.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();
 }

说明CLass如下:

@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数组,并且此键的名称为父节点。 有人可以建议我如何实现这一目标吗?

谢谢

1 个答案:

答案 0 :(得分:0)

我使用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;
}
}