1

我有这个方法:

@GET
@Path("/myservice")
@Produces(MediaType.APPLICATION_JSON)
public Response mysercice() {

   boolean userExists = false;
   CacheControl cacheControl = new CacheControl();
   cacheControl.setNoCache(true);
   cacheControl.setNoStore(true);

   JSONObject jsonObject = new JSONObject();
   jsonObject.put("userExists", userExists);
   return Response.ok(jsonObject, MediaType.APPLICATION_JSON).cacheControl(cacheControl).build();

}

在浏览器中访问方法的url时,得到{},表示对象为空。所以,我尝试使用:

return Response.ok(jsonObject.toString(), MediaType.APPLICATION_JSON).cacheControl(cacheControl).build();

所以,我进入浏览器 {"userExists" : false} 但我不明白为什么在简单地返回 JSONObject 时,我们在浏览器中得到一个空对象。

4

1 回答 1

2

大多数 JAX-RS 实现都带有用于将响应实体映射到 JSON 的提供程序。所以当你写:

return Response.ok(jsonObject, MediaType.APPLICATION_JSON).build();

您基本上是在请求 JAX-RS 提供程序JSONObject为您编组为 JSON。唯一的问题是它JSONObject并不是真的要以这种方式序列化。相反,它旨在用于逐步构建 JSON 表示,然后将该表示转换为 JSON 字符串值。你有两个选择:

  1. 创建一个 POJO,其中包含您要发送回客户端的所有字段。在您的方法中返回此 POJO,它将自动转换为 JSON (`return Response.ok(myPojo, MediaType.APPLICATION_JSON).build()

  2. 直接将 JSON 数据作为字符串返回(您已经在示例中执行了该操作)。

于 2013-02-18T16:57:51.283 回答