简体   繁体   中英

jackson fasterxml multiple elements with the same name

I need to generate XML that confirms to this XSD:

<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:

@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:

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

With a parent <Line> element in excess. 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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