Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 660
Hooli Avatar asked Oct 29 '25 09:10

Hooli


1 Answers

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>
like image 161
Sharon Ben Asher Avatar answered Oct 31 '25 04:10

Sharon Ben Asher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!