【问题标题】:Provide a GET method in JSON and XML在 JSON 和 XML 中提供 GET 方法
【发布时间】:2013-03-08 07:51:56
【问题描述】:

我正在使用 Jersey 开发 REST 服务。

所以,如果我有一个用户类型的对象(其中包含有关用户的信息),例如:

User userObj = new User();

我想通过 JSONXML 的 GET 方法提供该信息。

我已经可以使用 gson.toJson(userObj) 以 JSON 格式提供它。那么 XML 呢?

谢谢

【问题讨论】:

标签: java xml json rest get


【解决方案1】:

看看 JAXB API。它提供了一种使用简单的 getter/setter 方法将 XML 映射到类的方法。 http://jaxb.java.net/tutorial/section_1_1-Introduction.html#About%20JAXB

【讨论】:

  • 那么,我可以这样做:@GET @Path("/userinfo/{id}") @Produces({"application/xml", "application/json"}) public String getUserInfo(@PathParam("id") String id) { String users = null; User user = null; user = new UserManager().getUserInfo(id); JAXBContext jaxbContext = JAXBContext.newInstance(User.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(user, System.out); users = jaxbMarshaller.toString(); return users; }
  • +1 - 由于 JAXB 是 JAX-RS 的默认绑定层,您可以只返回一个 JAXB 模型类,JAX-RS 实现将利用 JAXB 将其转换为 XML:blog.bdoughan.com/2010/08/…
猜你喜欢
  • 1970-01-01
  • 2019-03-23
  • 1970-01-01
  • 2016-10-06
  • 2012-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多