【问题标题】:How always is returned an array instead of an object as json?如何总是返回一个数组而不是一个对象作为 json?
【发布时间】:2015-09-05 09:25:02
【问题描述】:

如果我的结果对象有多个值,则返回一个数组作为 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 返回?

【问题讨论】:

  • 如果您的接口定义数据以 json 数组的形式发送,则它始终是 json 数组,即使它只包含一个元素。从开发的角度来看,在任何情况下都更容易依赖返回的数组并检查长度。为什么服务应该对单个元素有不同的行为?
  • 我猜我的表达方式有误。我不想返回单个对象。我总是想返回一个数组。我的代码有不同的行为。
  • 如果你返回一个数组列表,它也应该返回一个 json 数组,也许球衣优化了一些东西
  • 你可以尝试创建一个新的返回类,其中包含你想要返回的数组,然后返回这个类的对象吗?
  • 查看此链接:jersey.java.net/documentation/1.19/json.html#d4e926。它在“5.2.2.1”部分讨论了您的问题。映射符号'。

标签: java json rest jersey


【解决方案1】:

我的问题解决了。我在我的项目中添加了如下新类:

@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;
    }

}

参考:herehere

【讨论】:

    猜你喜欢
    • 2019-05-18
    • 2016-05-03
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    相关资源
    最近更新 更多