Spring with XML - Return Elements outside of a List

Viewed 111

I'm developing a system that specification says that the entity XML traveled through the web service controller endpoints must be like this:

<SAAF>
    <vehicle>
        <Information>
            <Quantity>3</Quantity>  
        </Information>
        <Entry>
            [... entry variables ..]
        </Entry>
        <Entry>
            [... entry variables ..]
        </Entry>
        <Entry>
            [... entry variables ..]
        </Entry>
    </vehicle>    
</SAAF>

But, I only managed to do this:

<SAAF>
  <vehicle>
    <information>
      <quantity>3</quantity>
    </information>
    <entries>
        <entry>
            [...entry variables...]
        </entry>
        <entry>
            [...entry variables...]
        </entry>
        <entry>
            [...entry variables...]
        </entry>
    </entries>
  </vehicle>
</SAAF>

This is the VehicleRoot class:

import lombok.Data;

@Data
@XmlRootElement(name = "vehicle")
@XmlType(propOrder = { "Information", "Entries" })
public class VehicleRoot implements Serializable {
    
    private static final long serialVersionUID = 1L;

    private Information Information;

    private List<Entry> Entries;

}

1 - Is possible to send the <Entry></Entry> objects tags without wrapping them inside the "entries" list?

2 - Can I configure Spring to return the tags with capitalized name? "Entry" instead of "entry"? Is this even possible? I managed to do this by adding @JsonNaming(PropertyNamingStrategy.UpperCamelCaseStrategy.class) annotation in the VehicleRoot class

I would like to be able to change the system specification, but I'm afraid that I won't be able to do that...

1 Answers

UPDATED ANSWER WITH THE SOLUTION FOR THE CASE:

Simply create a getter for the desired List with the @JacksonXmlElementWrapper(useWrapping = false) annotation above it:

private List<Entry> Entries = new ArrayList<>();

@JacksonXmlElementWrapper(useWrapping = false)
public List<Entry> getEntries() {
    return this.Entries;
}

ORIGINAL ANSWER:

Jackson's XmlMapper has a special feature to enable or disable wrapping for xml lists.

@Bean
ObjectMapper xmlMapper() {
    return XmlMapper.builder()
        ...
        .defaultUseWrapper(false)
        ...
        .build();
}

If you use the default (autoconfigured) xmlMapper, you can add Jackson2ObjectMapperBuilderCustomizer with the same setting:

@Bean
Jackson2ObjectMapperBuilderCustomizer xmlWrapperCustomizer() {
    return mapperBuilder -> mapperBuilder.defaultUseWrapper(false);
}
Related