【系统学习SpringBoot】SpringBoot 对象转JSON输出

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】所以可以直接输出,,方便了许多。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鼠晓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值