1

Why MappingJackson2XmlView doesn't allow to convert model that contains more than one object ?
see MappingJackson2XmlView.class line 90 :
throw new IllegalStateException("Model contains more than one object to render, only one is supported");

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Khalilos
  • 721
  • 2
  • 9
  • 17

1 Answers1

1

This is because there's no default way to convert a list to XML: a document must have exactly one root element. While an unnamed list is a valid thing to return in JSON, it's not OK in XML. You need to specify an intermediate class to hold the list. If you use a MarshallingView with a Jaxb2Marshaller, you can do this and still offer raw JSON lists:

<property name="defaultViews">
    <list>
        <!-- JSON -->
        <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />

        <!-- XML -->
        <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
            <constructor-arg>
                <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
                    <property name="packagesToScan" value="example.model" />
                </bean>
            </constructor-arg>
        </bean>
    </list>
</property>

Here, example.model.FooCollection would just contain a list of example.model.Foo, and would define its own @XmlRootElement.

Community
  • 1
  • 1
z0r
  • 8,185
  • 4
  • 64
  • 83
  • Note that you'll probably also need to set up content negotiation as shown in this [question about `ContentNegotiationManagerFactoryBean`](http://stackoverflow.com/q/27669568/320036) – z0r May 24 '16 at 04:10