SpringBoot输出JSON
以往使用SpringMVC中开发时,对象转JSON需要配置很多东西
【1】添加FastJson/jackjson等第三方jar
【2】在配置文件中配置Controller扫描
【3】给方法添加@ResponseBody
配置FastJson还需要给配置文件中添加(很麻烦( ▼-▼ ))
<mvc:annotation-driven><mvc:message-converters><bean id="fastJsonHttpMessageConverter"class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"><property name="supportedMediaTypes"><list><value>text/html;charset=UTF-8</value><value>application/json;charset=UTF-8</value></list></property></bean></mvc:message-converters>
</mvc:annotation-driven>
还记得SpringBoot的宗旨?【零配置】
对于以上一长串配置,对于SpringBoot是不需要的,直接给方法添加注解即可使用
像SpringMVC一样编写Controller,,只需要修改注解为【@RestController】即可。
package xatu.zsl.controller;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xatu.zsl.entity.Student;import java.util.ArrayList;
import java.util.List;/*** Created by zsl on 2017/9/2.*/
@RestController
public class HelloController {@RequestMapping("/springboot")public String hello() {return "Hello SpringBoot!";}@GetMapping("/student_json")public List getStudentJson() {List<Student> students = new ArrayList<>();students.add(new Student("刘备", "1406001", 25));students.add(new Student("张飞", "1406001", 20));students.add(new Student("关羽", "1406001", 23));students.add(new Student("曹操", "1405001", 24));return students;}}
在原先HelloController上添加一个方法,,返回List就可以转Json输出了
测试结果如下图:
有点简单粗暴了?,,那就对了
回头看看@ResponseBody
学过SpringMVC的读者都知道,Controller需要配置ResponstBody才能够返回内容,否则会去找ViewResolver进行转view输出,此处是直接输出的,,??why
【@RestController】这个注解是一个组合注解
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//package org.springframework.web.bind.annotation;import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {String value() default "";
}
它包含了这两个注解【@Controller】【@ResponseBody】所以可以直接输出,,方便了许多。

















