Spring MVC返回对象JSON

 

@RestController 用于返回对象,会自动格式化为JSON

    @RequestMapping("/user2")
    public User2 user2(Model model){
        model.addAttribute("content", hello + "(第二种)");
        User2 user=new User2();
        user.setId(1);
        user.setName("tomas");
        user.setPwd("pwd");
        return user;
    }

@Control会默认返回jsp页面

想返回对象的话还需要加上@ResponseBody注解

    @RequestMapping("/user2")

    @ResponseBody
    public User2 user2(Model model){
        model.addAttribute("content", hello + "(第二种)");
        User2 user=new User2();
        user.setId(1);
        user.setName("tomas");
        user.setPwd("pwd");
        return user;
    }

返回结果一致:

{

  • id1,
  • name"tomas",
  • pwd"pwd"
}
原文地址:https://www.cnblogs.com/xmanblue/p/5303115.html