简体   繁体   English

在 Rest 服务中返回纯字符串不返回 json?

[英]Returning plain String in Rest service does not return json?

I created the following rest methods in my rest based web service我在基于 rest 的 web 服务中创建了以下 rest 方法

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

When I call plain service, it returns a raw string hello world rather than a JSON formatted output.当我调用普通服务时,它返回一个原始字符串hello world而不是 JSON 格式的 output。 However, wrapping the string in an object returns the JSON {"data":"hello world"}但是,将字符串包装在 object 中会返回 JSON {"data":"hello world"}

Why is it showing such a behaviour?为什么它会表现出这样的行为? How do I send the plain String as JSON?如何将纯字符串作为 JSON 发送?

I tried the above option, it does not work.我尝试了上述选项,它不起作用。

String result="hello world";
return result;

The reason why String is not getting auto-converted seems to be due to missing @XmlRootElement. String 没有自动转换的原因似乎是由于缺少@XmlRootElement。 Based on the docuementation in cxf http://cxf.apache.org/docs/jax-rs-data-bindings.html#JAX-RSDataBindings-HandlingJAXBbeanswithoutXmlRootElementannotations we need to use some jaxbElementClassMap.基于 cxf http://cxf.apache.org/docs/jax-rs-data-bindings.html#JAX-RSDataBindings-HandlingJAXBbeanswithoutXmlRootElementannotations中的文档,我们需要使用一些 jaxbElementClassMap。 But unable to find further details.但无法找到更多细节。

I think these will give you what you need.我认为这些会给你你所需要的。

@GET
@Produces("application/json")
@Path("plain")
public String getPlain()
{
return JSONObject.quote("Hello World");
}

OR或者

@GET
@Produces("application/json")
@Path("plain")
public String getPlain()
{
return "\"Hello World\"";
}

OR或者

@GET
@Produces("application/json")
@Path("plain")
public char[] getPlain()
{
return "Hello World!".toCharArray();
}

Try this尝试这个

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

JSON needs a key-value pair. JSON 需要一个键值对。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM