RESTful Web 服务如何正确生成 JSON? [英] How correctly produce JSON by RESTful web service?

查看:42
本文介绍了RESTful Web 服务如何正确生成 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是第一次编写 Web 服务.我创建了一个基于 Jersey 的 RESTful Web 服务.我想生成 JSON.我需要做什么才能为我的网络服务生成正确的 JSON 类型?

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']}";
}

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

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/用户指南.html#json

这篇关于RESTful Web 服务如何正确生成 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆