Java-Jackson 将 ArrayList<String> 序列化为具有不同子项名称的 XML

huangapple go评论123阅读模式
英文:

Java-Jackson Serialize ArrayList<String> to XML with different child names

问题

我一直在使用jackson-dataformatter-v2.9.10将Java类序列化为XML字符串。

这是我的类:

public class parent()
{
    public ArrayList&lt;String&gt; children;

    public parent() {
        children = new ArrayList&lt;String&gt;();
    }
}

这是我想要实现的:

<parent>
    <children>
        <child>John</child>
        <child>Ben</child>
        <child>Mary</child>
    </children>
</parent>

这是我得到的:

<parent>
    <children>
        <children>John</children>
        <children>Ben</children>
        <children>Mary</children>
    </children>
</parent>

有关如何更改ArrayList children元素名称的建议吗?

英文:

I've been using jackson-dataformatter-v2.9.10 to serialize a Java class into an XML string.

This is my class:

public class parent()
{
    public ArrayList&lt;String&gt; children;

    public parent() {
       
         children = new ArrayList&lt;String&gt;();
    }
}

Here is what I want to achieve:

&lt;parent&gt;
    &lt;children&gt;
      &lt;child&gt;John&lt;/child&gt;
      &lt;child&gt;Ben&lt;/child&gt;
      &lt;child&gt;Mary&lt;/child&gt;
    &lt;/children&gt;
&lt;/parent&gt;

Here is what I'm getting:

&lt;parent&gt;
    &lt;children&gt;
      &lt;children&gt;John&lt;/children&gt;
      &lt;children&gt;Ben&lt;/children&gt;
      &lt;children&gt;Mary&lt;/children&gt;
    &lt;/children&gt;
&lt;/parent&gt;

Any suggestion on how to change the ArrayList children element names?

答案1

得分: 2

使用@JacksonXmlElementWrapper@JacksonXmlProperty同时应用于列表字段。

以下是示例代码:

	@JacksonXmlElementWrapper(localName = "children")
	@JacksonXmlProperty(localName = "child")
	private List<String> child = new LinkedList<>();

ElementWrapper用于外部元素
(包含重复元素的元素)。
XmlProperty用于内部元素
(重复的元素)。

英文:

Use both @JacksonXmlElementWrapper and @JacksonXmlProperty on the list field.

Here is some sample code:

	@JacksonXmlElementWrapper(localName = &quot;children&quot;)
	@JacksonXmlProperty(localName = &quot;child&quot;)
	private List&lt;String&gt; child = new LinkedList&lt;&gt;();

The ElementWrapper is for the outer element
(the one that contains the repeating elements).
The XmlProperty is for the inner element
(the one that repeats).

答案2

得分: 0

你应该能够使用

@JacksonXmlElementWrapper(localName = "children")
List<String> child;

https://stackify.com/java-xml-jackson

英文:

You should be able to use

@JacksonXmlElementWrapper(localName = &quot;children&quot;)
List&lt;String&gt; child;

https://stackify.com/java-xml-jackson

huangapple
  • 本文由 发表于 2020年8月7日 01:11:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63288616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定