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");
Asked
Active
Viewed 632 times
1
1 Answers
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
.
-
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