简体   繁体   English

在Java中提供RESTful JSON API

[英]Providing RESTful JSON API in Java

What is the idiomatic way of providing RESTful JSON API in Java? 在Java中提供RESTful JSON API的惯用方法是什么? Do you use JAX-WS and XML annotations (@XmlElement etc.)? 您是否使用JAX-WS和XML注释(@XmlElement等)? How do you serialize annotated objects to JSON (using Jackson or similar library)? 如何将带注释的对象序列化为JSON(使用Jackson或类似的库)? How do you separate domain objects from objects sent out to API? 如何将域对象与发送给API的对象分开?

I know Java, I would like you to point me out to good resources and best practices about these topics. 我了解Java,我希望您指出有关这些主题的良好资源和最佳实践。

Thank you! 谢谢!

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 Jackson with Spring as parser. 顺便说一下,我用Jackson和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: 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: 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
  }
}

I would simply use Play to save me a lot of work that has already been done. 我只是使用Play为我节省了很多已经完成的工作。 The link is for Play 1.2 and while the current version is 2.1, it should be fit for that as well. 该链接适用于Play 1.2,而当前版本为2.1,它也应该适合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM