【发布时间】:2013-03-08 07:51:56
【问题描述】:
我正在使用 Jersey 开发 REST 服务。
所以,如果我有一个用户类型的对象(其中包含有关用户的信息),例如:
User userObj = new User();
我想通过 JSON 和 XML 的 GET 方法提供该信息。
我已经可以使用 gson.toJson(userObj) 以 JSON 格式提供它。那么 XML 呢?
谢谢
【问题讨论】:
我正在使用 Jersey 开发 REST 服务。
所以,如果我有一个用户类型的对象(其中包含有关用户的信息),例如:
User userObj = new User();
我想通过 JSON 和 XML 的 GET 方法提供该信息。
我已经可以使用 gson.toJson(userObj) 以 JSON 格式提供它。那么 XML 呢?
谢谢
【问题讨论】:
看看 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; }