我在基于休息的网络服务中创建了以下休息方法
@GET
@Produces("application/json")
@Path("plain")
public String getPlain()
{
return "hello world";
}
@GET
@Produces("application/json")
@Path("wrapper")
public Response getWrapper()
{
return Response.ok(new Object(){ public String data = "hello world";}).build();
}
当我调用普通服务时,它返回原始字符串 hello world 而不是 JSON 格式的输出。但是,将字符串包装在对象中会返回 JSON {"data":"hello world"}
为什么会出现这样的行为?如何将纯字符串作为 JSON 发送?
最佳答案
我认为这些会满足您的需求。
@GET
@Produces("application/json")
@Path("plain")
public String getPlain()
{
return JSONObject.quote("Hello World");
}
或
@GET
@Produces("application/json")
@Path("plain")
public String getPlain()
{
return "\"Hello World\"";
}
或
@GET
@Produces("application/json")
@Path("plain")
public char[] getPlain()
{
return "Hello World!".toCharArray();
}
关于java - 在 Rest 服务中返回纯字符串不返回 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12535870/