【问题标题】:Returning plain String in Rest service does not return json?在 Rest 服务中返回纯字符串不返回 json?
【发布时间】:2012-09-21 18:07:58
【问题描述】:

我在我的基于休息的网络服务中创建了以下休息方法

@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 发送?

【问题讨论】:

  • 您是否尝试删除 @Produces 注释?
  • 当我想要的只是一个 json 时,为什么我要删除 @Produces 注释?不管怎样,我试了一下......没有帮助。
  • 是什么让您认为“hello world”不是有效的 JSON?
  • @albogdano "hello world" 是有效的 json,但 hello world 不是。他说端点返回后者

标签: java rest


【解决方案1】:

我尝试了上面的选项,它不起作用。

String result="hello world";
return result;

String 没有自动转换的原因似乎是由于缺少@XmlRootElement。根据 cxf http://cxf.apache.org/docs/jax-rs-data-bindings.html#JAX-RSDataBindings-HandlingJAXBbeanswithoutXmlRootElementannotations 中的文档,我们需要使用一些 jaxbElementClassMap。但无法找到更多详细信息。

【讨论】:

    【解决方案2】:

    试试这个

    @GET 
    @Produces("application/json") 
    @Path("plain") 
    public String getPlain() 
    { 
    String result= "hello world";
        return result;
    } 
    

    JSON 需要一个键值对。

    【讨论】:

    • JSON 需要一个键值对或一个数组
    • @DavidGrant 是的,上面问题上下文中的键值对。
    • @DavidGrant:JSON 值可以是任何 JSON 值。实现是否支持对象(或数组)以外的根值是另一回事。
    • ... 另外,在您的示例中没有键值对。只有一个字符串
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    相关资源
    最近更新 更多