我正在使用春季和平针织物。这个组合的问题在于尝试创建一个json,其中一个对象具有List并且只有一个元素。如果有很多,json很好。泽西岛“忘了”在单个元素上添加括号[]。
正如你所看到的,甚至试图强迫它使用jackson(正如我在很多教程中读到的那样),但是......同样的结果:
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>org.codehaus.jackson.jaxrs;au.com.bikesquare.core.rest</param-value>
</init-param>
</servlet>
然后找到了这个,但仍然没有。
@Provider
@Component
@Produces ("application/json")
public class JsonJaxbResolver implements ContextResolver<JAXBContext> {
@Override
public JAXBContext getContext(Class<?> type) {
JSONConfiguration.MappedBuilder b = JSONConfiguration.mapped();
b.arrays("to");
try {
return new JSONJAXBContext(b.build(), EmailMessageTransferObject.class);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
我尝试发送我的对象(包含列表)的服务器捕获了这个:
....
"to": {
"email": "aaa@bbb.ccc",
"name": "aaa"
}
....
原定于:
"to": [
{
"email": "aaa@bbb.ccc",
"name": "aaa"
}
],
我的班级(部分内容):
@XmlRootElement
public class EmailMessageTransferObject {
...
@XmlElement
private List<EmailRecipientTransferObject> to;
...
}
有什么想法吗? TNX
答案 0 :(得分:0)
稍后找到答案:
@Provider
@Produces ("application/json")
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
private JAXBContext context;
private Class<?>[] types = {SendEmailMessageTransferObject.class};
public JAXBContextResolver() throws Exception {
this.context = new JSONJAXBContext(JSONConfiguration.mapped().arrays("to").build(), types);
}
@Override
public JAXBContext getContext(Class objectType) {
for (Class type : types) {
if (type == objectType) {
return context;
}
}
return null;
}
}
客户端:
public MandrillRestMailImpl() {
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getClasses().add(JAXBContextResolver.class);
client = Client.create(clientConfig);
client.addFilter(new LoggingFilter(System.out)); //todo: remove this for prod
}