[英]Return simple string in web API producing application/json
In the specification, the answer of the API is a simple string value, but the format is JSON. 在规范中,API的答案是一个简单的字符串值,但格式是JSON。
I'm using Jersey. 我正在使用泽西岛。
If I construct my answer like that: 如果我构建我的答案:
return Response.ok().entity("hello").build();
It's working, but for example, in the network view of Firefox, when I look at the answer, there is a JSON syntax error. 它正在运行,但是例如,在Firefox的网络视图中,当我查看答案时,会出现JSON语法错误。 If I had some double quotes to the string like that:
如果我对字符串有一些双引号:
return Response.ok().entity("\"hello\"").build();
There is no syntax error in Firefox, but I don't think it's a good way to do it. Firefox中没有语法错误,但我认为这不是一个好方法。
Is there a good way to return a simple String value for an API producing some JSON? 是否有一种很好的方法可以为生成一些JSON的API返回一个简单的String值?
if you're going to produces JSON then you have to return some Object or Collection, for example: 如果您要生成JSON,那么您必须返回一些Object或Collection,例如:
Hello.java Hello.java
public class Hello{
public String name;
// getter setter
}
in YourRest.java 在YourRest.java中
@GET
@Path("hello/{name}")
@Produces(MediaType.APPLICATION_JSON)
public String greeting(@PathParam("name") String name ){
Hello hello = new Hello();
hello.setName(name);
return Response.ok().entity(hello).build();
}
@GET
@Path("people")
@Produces(MediaType.APPLICATION_JSON)
public ArrayList<String> peopleList(){
List<String> people = new ArrayList<String>();
Hello hello = new Hello();
hello.setName("bloub");
people.add(hello);
hello.setName("Aime");
people.add(hello);
return Response.ok().entity(people).build();
}
http://localhost:8080/hello/bloub will return http:// localhost:8080 / hello / bloub将返回
{
"name" : "bloub"
}
http://localhost:8080/people will return http:// localhost:8080 /人们将返回
[
{
"name" : "bloub"
},
{
"name" : "Aime"
}
]
but if you want to return simple text then use @Produces(MediaType.TEXT_PLAIN)
但如果要返回简单文本,请使用
@Produces(MediaType.TEXT_PLAIN)
for example: 例如:
in YourRest.java 在YourRest.java中
@GET
@Path("hello/{name}")
@Produces(MediaType.TEXT_PLAIN)
public String greeting(@PathParam("name") String name ){
return Response.ok().entity("Hello, "+name).build();
}
http://localhost:8080/hello/bloub will return http:// localhost:8080 / hello / bloub将返回
Hello, bloub
Hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.