[英]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.