微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

@responsebody json xml

@ResponseBody 是 Spring MVC 中的注解,用于指示 Controller 方法返回的对象应该封装为哪种格式的数据。它可以返回 JSON、XML 或者直接字符串。

@responsebody json xml

当返回 JSON 格式时,我们需要在方法添加@ResponseBody@RequestMapping注解,并使用@JsonView注解来指定返回的字段。

@ResponseBody
@RequestMapping("/user")
@JsonView(UserVO.UserInfo.class)
public UserVO getUserById(@PathVariable("id") Long id) {
    return userService.getUserById(id);
}

当返回 XML 格式时,我们和返回 JSON 格式相似需要在方法添加@ResponseBody@RequestMapping注解,并使用JAXB 来序列化对象。

@ResponseBody
@RequestMapping("/user.xml")
public UserVO getUserByIdAsXml(@PathVariable("id") Long id) throws JAXBException {
    UserVO userVO = userService.getUserById(id);
    JAXBContext jaxbContext = JAXBContext.newInstance(UserVO.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
    StringWriter sw = new StringWriter();
    marshaller.marshal(userVO,sw);
    return userVO;
}

你可以指定一个包含所有响应字段的注解类,然后使用该类的注解来返回 JSON 和 XML。在本例中,我使用UserVO.UserInfo.class

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐