[英]How always is returned an array instead of an object as json?
如果我的结果对象有多个值,则返回一个数组作为 json。 但是如果我的结果对象只有一个值,则返回一个对象作为 json。 我不想返回单个对象。 我总是想返回一个数组。
我的代码如下:
@Service
@Path("/item")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Scope("request")
public class MyResource {
@GET
@Path("/ac")
public List<ACResult> getACResults(@QueryParam("term") String term) {
List<MyResultClass> result = new ArrayList<>();
...
return result;
}
}
我使用球衣 1.18.3
当存在单个对象时,如何始终将数组而不是对象作为 json 返回?
我的问题解决了。 我在我的项目中添加了新类,如下所示:
@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
private JAXBContext context;
private final Class[] types = {MyResultClass.class};
public JAXBContextResolver() throws Exception {
this.context = new JSONJAXBContext(JSONConfiguration.mapped().arrays("myJsonKey").build(), types);
}
@Override
public JAXBContext getContext(final Class objectType) {
for (Class type : types) {
if (type == objectType) {
return context;
}
}
return null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.