如何通过RESTful Web服务正确生成JSON? [英] How correctly produce JSON by RESTful web service?
问题描述
我第一次写网络服务。我创建了一个基于 Jersey 的RESTful Web服务。我想生成JSON 。如何生成正确的JSON类型的Web服务需要做什么?
I am writing a web service the first time. I created a RESTful web service based on Jersey. And I want to produce JSON. What do I need to do to generate the correct JSON type of my web service?
这是我的方法之一:
@GET
@Path("/friends")
@Produces("application/json")
public String getFriends() {
return "{'friends': ['Michael', 'Tom', 'Daniel', 'John', 'Nick']}";
}
我只需指出注释 @就足够了为我的方法生成(application / json)
?那么这个方法可能会返回任何类型的对象?还是只有String?我是否需要对这些对象进行额外处理或转换?
Is it sufficient that I simply point out annotation @Produces("application/json")
for my method? Then this method may return any type of object? Or only String? Do I need additional processing or transformation of these objects?
请帮助我作为初学者来处理这些问题。在此先感谢!
Please help me as a beginner to deal with these issues. Thanks in advance!
推荐答案
您可以使用jaxb注释来注释您的bean。
You can annotate your bean with jaxb annotations.
@XmlRootElement
public class MyJaxbBean {
public String name;
public int age;
public MyJaxbBean() {} // JAXB needs this
public MyJaxbBean(String name, int age) {
this.name = name;
this.age = age;
}
}
然后您的方法如下所示:
and then your method would look like this:
@GET @Produces("application/json")
public MyJaxbBean getMyBean() {
return new MyJaxbBean("Agamemnon", 32);
}
最新文档中有一章涉及此问题:
There is a chapter in the latest documentation that deals with this:
https:// jersey .java.net / documentation / latest / user-guide.html #json
这篇关于如何通过RESTful Web服务正确生成JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!