简体   繁体   English

杰克逊fasterxml具有相同名称的多个元素

[英]jackson fasterxml multiple elements with the same name

I need to generate XML that confirms to this XSD: 我需要生成确认此XSD的XML:

<xsd:element name="Line" type="Line" minOccurs="0" maxOccurs="3"/>

So that the output is like: 这样的输出就像:

<root>
    <Line>A</Line>
    <Line>B</Line>
    <Line>C</Line>
</root>

The problem is that if I annotate the variables in the Java bean like: 问题是,如果我注释Java bean中的变量,例如:

@JsonProperty("Line")
private String Line1;

@JsonProperty("Line")
private String Line2;

@JsonProperty("Line")
private String Line3;

Then I get an exception and if I use a List then the output comes out wrong, like: 然后我得到一个异常,如果我使用List则输出结果错误,例如:

   <root>
       <Line>
           <Line>1 New Orchard Road</Line>
           <Line>Armonk</Line>
       </Line>
   </root>

With a parent <Line> element in excess. <Line>元素过多。 Is there a way around this? 有没有解决的办法?

All you need is the proper jackson annotation: 您只需要适当的杰克逊注释即可:

public class ListTest
{
    @JacksonXmlElementWrapper(useWrapping = false)
    public List<String> line = new ArrayList<>();
}

testing: 测试:

public static void main(String[] args)
{
    JacksonXmlModule module = new JacksonXmlModule();
    XmlMapper mapper = new XmlMapper(module);
    ListTest lt = new ListTest();
    lt.line.add("A");
    lt.line.add("B");
    lt.line.add("C");
    try {
        mapper.writeValue(System.out, lt);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

output: 输出:

<ListTest><line>A</line><line>B</line><line>C</line></ListTest>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM