返回JSONObject时浏览器中的空对象 [英] Empty object in browser when returning JSONObject

查看:304
本文介绍了返回JSONObject时浏览器中的空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种方法:

@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时,我得到{},这意味着该对象为空. 因此,我尝试使用:

When accessing to the URL of the method in the browser, I get { }, it means that the object is empty. So, I tried to use :

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

因此,我进入浏览器{"userExists":false} 但是我不明白为什么当仅返回JSONObject时,我们在浏览器中会得到一个空对象.

So, I get in the browser {"userExists" : false} But I didn't understand why when returning simply the JSONObject, we get in the browser an empty object.

推荐答案

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

Most JAX-RS implementations come with a provider for mapping response entities to JSON. So when you write:

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

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

You are basically requesting that the JAX-RS provider marshall the JSONObject into JSON for you. The only problem being that JSONObject isn't really meant to be serialized this way. Instead its meant to be used to build a JSON representation incrementally, then convert that representation into a JSON string value. You have two options:

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

  1. Create a POJO containing all the fields you want to send back to the client. Return this POJO in your method and it will be automatically converted to JSON (`return Response.ok(myPojo, MediaType.APPLICATION_JSON).build()

直接以字符串形式返回JSON数据(在您的示例中已经完成了此操作).

Return the JSON data directly as a String (which you already did in your example that works).

这篇关于返回JSONObject时浏览器中的空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆