membersound
membersound

Reputation: 86727

Jackson serializer wrapping lists by default?

I'm using spring with RestTemplate to postForEntity(req, rsp) xml to a webservice.

@Bean
public Jackson2ObjectMapperBuilderCustomizer initJackson() {
    return (builder) -> builder.modules(new JaxbAnnotationModule());
}

The java bean is autogenerated from xsd files using xsdtojava. Thus I cannot modify the generated class!

Problem: The

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@Generated
public class MyRequest {
    @XmlElement(required = true)
    private SubReq subs;

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType
    public static class SubReq {
        private List<String> list;
    }
}

Result: the <list> element contains additional nested <list> elements. But why? And how can I prevent?

Current:

<MyRequest>
    <SubReq>
        <list>  
            <list>val1</list>
            <list>val2</list>
        </list>
    </SubReq>
</MyRequest>

My goal:

<MyRequest>
    <SubReq>
        <list>val1</list>
        <list>val2</list>
    </SubReq>
</MyRequest>

How can I configure jackson to not wrap the lists inside?

The MyRequest element is autogenerated from:

<xs:schema>
    <xs:element name="MyRequest">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="SubReq">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="list" minOccurs="0" maxOccurs="unbounded">
                                <xs:simpleType>
                                    <xs:restriction base="xs:string" />
                                </xs:simpleType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    ...
</xs:schema>

Upvotes: 2

Views: 2615

Answers (2)

membersound
membersound

Reputation: 86727

I solved it by disabling unwrapper grobally with defaultUseWrapper(false):

@Bean
public Jackson2ObjectMapperBuilderCustomizer initJackson() {
    return (builder) -> builder.modules(new JaxbAnnotationModule())
                    .defaultUseWrapper(false);
}

Upvotes: 4

Naman
Naman

Reputation: 31878

You can set the DeserializationFeature.UNWRAP_ROOT_VALUE to true for this :

objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);

The default value of this attribute is true.

This is under a restriction that preferably I would have annotated such fields with @JsonUnwrapped while generating the code itself.

Upvotes: 0

Related Questions