如何通过RESTful Web服务正确生成JSON?

时间:2012-11-27 23:14:23

标签: java json web-services rest jersey

我第一次写网络服务。我基于Jersey创建了一个RESTful Web服务。我想生成JSON 。如何生成正确的JSON类型的Web服务?

这是我的一种方法:

@GET
@Path("/friends")
@Produces("application/json")
public String getFriends() {
    return "{'friends': ['Michael', 'Tom', 'Daniel', 'John', 'Nick']}";
}

我只是为我的方法指出注释@Produces("application/json")是否足够?那么这个方法可能会返回任何类型的对象?还是只有String?我是否需要对这些对象进行额外处理或转换?

作为初学者,请帮助我处理这些问题。提前谢谢!

5 个答案:

答案 0 :(得分:31)

您可以使用jaxb注释来注释bean。

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

然后您的方法将如下所示:

   @GET @Produces("application/json")
   public MyJaxbBean getMyBean() {
      return new MyJaxbBean("Agamemnon", 32);
   }

最新文档中有一章涉及此问题:

https://jersey.java.net/documentation/latest/user-guide.html#json

答案 1 :(得分:5)

您可以使用org.json http://www.json.org/java/

等软件包

因为您需要更频繁地使用JSONObject。

在那里,您可以轻松创建JSONObjects并在其中添加一些值:

 JSONObject json = new JSONObject();
 JSONArray array=new JSONArray();
    array.put("1");
    array.put("2");
    json.put("friends", array);

    System.out.println(json.toString(2));


    {"friends": [
      "1",
      "2"
    ]}

编辑这样做的好处是,您可以在不同的图层中构建响应并将其作为对象返回

答案 2 :(得分:4)

@GET
@Path("/friends")
@Produces(MediaType.APPLICATION_JSON)
public String getFriends() {

    // here you can return any bean also it will automatically convert into json 
    return "{'friends': ['Michael', 'Tom', 'Daniel', 'John', 'Nick']}";
}

答案 3 :(得分:1)

@POST
@Path ("Employee")
@Consumes("application/json")
@Produces("application/json")
public JSONObject postEmployee(JSONObject jsonObject)throws Exception{
    return jsonObject;
}       

答案 4 :(得分:0)

使用此注释

if(context == null){ context = new ApplicationDbContext(); }
相关问题