【发布时间】:2012-06-07 17:12:12
【问题描述】:
我正在从 WSDL 创建 Web 服务客户端,并且我想将从 SOAP 调用获得的 XML 转换为 JSON 对象(作为 RESTful WS)。
我尝试过 GSON,但它坚持使用 TypeAdapter。因为我有大约 75 个对象,所以我需要更通用的东西。我也使用过 Jackson,但它只是将其作为 XML 发送。
NetBeans (wsimport) 生成许多类,下面显示了其中的示例。如何将其转换为 JSON 对象?
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "addressData", propOrder = {
"addressLine1",
"addressLine2"
})
public class AddressData {
@XmlElement(required = true)
protected String addressLine1;
@XmlElementRef(name = "addressLine2", type = JAXBElement.class, required = false)
protected JAXBElement<String> addressLine2;
/**
* Gets the value of the addressLine1 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddressLine1() {
return addressLine1;
}
/**
* Sets the value of the addressLine1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddressLine1(String value) {
this.addressLine1 = value;
}
/**
* Gets the value of the addressLine2 property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getAddressLine2() {
return addressLine2;
}
/**
* Sets the value of the addressLine2 property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setAddressLine2(JAXBElement<String> value) {
this.addressLine2 = value;
}
}
【问题讨论】:
-
“我也使用过 Jackson,但它只是将它作为 XML 原封不动地发送出去。”那你还没有正确配置jackson;它可以处理 JAXB 注释。你尝试了什么?
-
我的印象是,如果我在方法签名中使用 @ResponseBody 表示法,它是自动的。你能告诉我我需要对杰克逊采取什么行动吗?
-
如果你使用 spring-mvc 3.1 并且在你的配置中有
mvc:annotation-driven,它可能是自动的,但你仍然需要确保你发送正确的 HTTP 头 (Accept: application/json)。如果您已经这样做了,但它仍然不是自动的,您可能需要配置AnnotationMethodHandlerAdapter与杰克逊messageConverter -
这就是答案(带有杰克逊消息转换器的 AnnotationMethodHandlerAdapter)。非常感谢。
标签: java xml xml-serialization