在 Java 中提供 RESTful JSON API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17083844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:54:57  来源:igfitidea点击:

Providing RESTful JSON API in Java

javajsonweb-servicesapi

提问by Jakub Kulhan

What is the idiomatic way of providing RESTful JSON API in Java? Do you use JAX-WS and XML annotations (@XmlElement etc.)? How do you serialize annotated objects to JSON (using Hymanson or similar library)? How do you separate domain objects from objects sent out to API?

在 Java 中提供 RESTful JSON API 的惯用方式是什么?您是否使用 JAX-WS 和 XML 注释(@XmlElement 等)?您如何将带注释的对象序列化为 JSON(使用 Hymanson 或类似库)?如何将域对象与发送到 API 的对象分开?

I know Java, I would like you to point me out to good resources and best practices about these topics.

我了解 Java,我希望您向我指出有关这些主题的良好资源和最佳实践。

Thank you!

谢谢!

采纳答案by Enrichman

I have used happily Jersey/JAX-RS but I would suggest you Spring MVC 3, not only for the rest api support but also for other interesting stuff as IoC or beans that could turn out to be useful.

我已经愉快地使用了 Jersey/JAX-RS,但我建议你使用Spring MVC 3,不仅是为了其余的 api 支持,而且还有其他有趣的东西,如 IoC 或可能有用的 bean。

Here a link where to refer: http://blog.springsource.org/2009/03/08/rest-in-spring-3-mvc/

这里有一个参考链接:http: //blog.springsource.org/2009/03/08/rest-in-spring-3-mvc/

Btw, I've used Hymanson with Spring as parser. :)

顺便说一句,我已经将 Hymanson 与 Spring 一起用作解析器。:)



A bit of code (basically mark your bean, as you said, with @XmlRootElement and use @Path to mark the API)

一些代码(基本上像你说的那样用@XmlRootElement 标记你的bean,并使用@Path 来标记API)

JAX-RS

JAX-RS

bean:

豆角,扁豆:

@XmlRootElement
public class Response {

  private String result;
  private String message;

  //getter and setter
}

api:

接口:

@Path("rest/user")
@Produces(MediaType.APPLICATION_JSON)
public class UserService {

  @POST
  @Path("/login")
  public Response login(
        @FormParam("username") String username,
        @FormParam("password") String password
  ) {
      // Your logic here
  }
}

Spring

春天

api:

接口:

@Controller
@RequestMapping("/user")
public class UserService {

  @RequestMapping(method = RequestMethod.POST, value="/login", headers="Accept=application/json")
  public @ResponseBody Response login(
        @RequestParam(value = "user", defaultValue = "") String email,
        @RequestParam(value = "password", defaultValue = "") String password,
        HttpServletRequest request
        ) {
    // Your logic here
  }
}

回答by Machisuji

I would simply use Playto save me a lot of work that has already been done. The link is for Play 1.2 and while the current version is 2.1, it should be fit for that as well.

我会简单地使用Play来为我节省大量已经完成的工作。该链接适用于 Play 1.2,而当前版本是 2.1,它也应该适用于该版本。