1

请帮助我了解 Spring 中 XML&Json 根元素的名称发生了什么

在 JSON 中我得到

{"addressList":
 [{"StreetName":"Boul. Rene-Levesque Ouest","AddressID":1,"StreetNumber":1350},

在 XML 我得到

<list>
  <Address2>
  <StreetName>Boul. Rene-Levesque Ouest</StreetName>
  <AddressID>1</AddressID>
  <StreetNumber>1350</StreetNumber>
</Address2>

但我想得到

{"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>

这是我使用 mvn clean package jetty:run 运行的代码

地址.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;
}

地址控制器.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>
4

1 回答 1

0

这可能不是最好的解决方案,但您可以尝试将您的地址包装在一个容器对象中,例如:

public class AddressList {
    List<Address> addressList
}
于 2013-05-20T20:49:57.400 回答