springboot如何返回json数据

2023-08-15

  1. 使用@ResponseBody注解



      该注解用于将 Controller 的方法返回的对象,通过 HttpMessageConverter 接口转换为指定格式的数据如:json,xml 等,通过 Response 响应给客户端在controller的方法上增加@RespongBody

@RequestMapping("/findAll.do")
@ResponseBody
public List<SysCategory> findAll(){
        //查询分类信息,具体的service层方法略
        List<SysCategory> categoryList = categoryService.findAll();
        System.out.println(categoryList);
        return categoryList;
}



2. 使用@RestController注解


@RestController是@ResponseBody和@Controller两者的结合,使用这个注解后就无需再用那两个注解。

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/findAll.do")
    public List<SysCategory> findAll(){
        List<SysCategory> categoryList = categoryService.findAll();
        System.out.println(categoryList);
        return categoryList;
    }
}



3.使用response将数据写回客户端(不推荐)

String obj = "[SysCategory{id=1, name='JavaSe'}, SysCategory{id=2, name='JavaEE'}, SysCategory{id=3, name='前端'}, SysCategory{id=4, name='其他'}]"
ObjectMapper mapper = new ObjectMapper();
response.setContentType("application/json;charset=utf-8");
mapper.writeValue(response.getOutputStream(),obj);




联系信息

QQ:1827566828
Email: 1827566828@qq.com
Web: https://www.yynet.wang

留言