问题
Please help me to understand what is going on with name of XML&Json root element in Spring
in JSon I get
{"addressList":
[{"StreetName":"Boul. Rene-Levesque Ouest","AddressID":1,"StreetNumber":1350},
in XML I get
<list>
<Address2>
<StreetName>Boul. Rene-Levesque Ouest</StreetName>
<AddressID>1</AddressID>
<StreetNumber>1350</StreetNumber>
</Address2>
but I want to get
{"AddressList":
[{"StreetName":"Boul. Rene-Levesque Ouest","AddressID":1,"StreetNumber":1350},
XML:
<AddressList>
<Address>
<StreetName>Boul. Rene-Levesque Ouest</StreetName>
<AddressID>1</AddressID>
<StreetNumber>1350</StreetNumber>
</Address>
Here is my code that I run using mvn clean package jetty:run
Address.java
@XmlRootElement(name="AddressList")
@XStreamAlias("AddressList")
@JsonAutoDetect(fieldVisibility=Visibility.ANY, getterVisibility=Visibility.NONE,
isGetterVisibility=Visibility.NONE)
@JsonRootName(value = "AddressList")
public class Address {
private String StreetName;
private Integer AddressID;
private Integer StreetNumber;
}
AddressController.java
@Controller
@XStreamAlias("AddressList")
public class AddressController {
@RequestMapping(value="/Address", method=RequestMethod.GET)
public List<Address> getAllAddress() {
return returnData(null);
}
@RequestMapping(value="/Address({id})", method=RequestMethod.GET)
public List<Address> getAddressById(@PathVariable String id) {
return returnData(id);
}
}
Spring-Servlet.xml
<context:component-scan base-package="org.test1.server1" />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="defaultContentType" value="application/json" />
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
<!-- <entry key="atom" value="application/atom+xml"/> -->
</map>
</property>
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
<!-- XML View -->
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true"/>
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>
回答1:
This might not be the best solution, but you could try wrapping your addresses in a container object, eg:
public class AddressList {
List<Address> addressList
}
来源:https://stackoverflow.com/questions/16657281/cant-rename-xml-json-root-element-in-spring-3-2-2-jackson-2-2-and-xstream