Spring Boot (二) - 返回json数据及自定义json解析

前言

上一篇介绍了如何初始化一个spring boot 项目,这一节说明一下在spring boot中返回json数据及自定义json解析框架。

实践

涉及知识点:

  • @RestController注解
  • @ResponseBody注解
  • 自定义json解析

内置解析

先创建一个实体类

package com.example.demo.pojo;  

/**
 * @author ashinlee
 * @date 2018/3/26
 * @time 21:49
 */
public class Student {
    private String name;
    private int age;
    private double score;

   //setter,getter,toString省略,ide自动生成即可
}

回到上一篇中的controller,添加getStudent方法

package com.example.demo.controller;

import com.example.demo.pojo.Student;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author AshinLee
 * @date 2018/3/24
 * @time 9:41
 */
@RestController
public class HelloController {

    @GetMapping("")
    public String hello(){
        return "hello";
    }

    /**
     * 获得指定id的学生
     * @param id
     * @return
     */
    @GetMapping("/student/{id}")
    public Object getStudent(@PathVariable int id){
        Student student = new Student();
        student.setId(id);
        student.setName("ashin");
        student.setScore(100d);
        return student;
    }
}

写完运行springboot 启动类(@SpringBpptApplication标注的类)

运行完成在浏览器输入:http://localhost:8080/student/1

就会返回:{“name”:”ashin”,”id”:1,”score”:100.0}

在Java中如果标注一个类为controller并加入容器那么就会使用@Controller注解,如果要让请求的一个方法返回json数据,那么我们会在方法上加上@ResponseBody注解,那么如果一个类中多个地方都要返回json数据,特别是写移动端后端的时候我们就可以将@Controller替换为@RestController ,@ResponseBody就不需要再写了。

自定义解析

检查spring boot父工程的依赖显示spring boot 默认用的是jackson

  <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.4</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-jdk8</artifactId>
      <version>2.9.4</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-jsr310</artifactId>
      <version>2.9.4</version>
      <scope>compile</scope>
    </dependency>

那么比如我们习惯使用fastjson(阿里巴巴开源),那么就得自己去定义解析。

 <dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.15</version>
 </dependency>

引入fastjson依赖(不了解maven的再次提醒自行补充)

在启动类继承WebMvcConfigurerAdapter

但在最近新出的 2.0.0版本中该类废弃了需要继承WebMvcConfigurationSupport

package com.example.demo;

import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

@SpringBootApplication
public class DemoApplication extends WebMvcConfigurationSupport {


    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setFeatures(Feature.SupportArrayToBean);//这边可以自己定义
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastJsonHttpMessageConverter);
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

这样就可以了,修改实体类测试

package com.example.demo.pojo;

import com.alibaba.fastjson.annotation.JSONField;

/**
 * @author ashinlee
 * @date 2018/3/26
 * @time 21:49
 */
public class Student {
    @JSONField(serialize = false) //不进行解析
    private String name;
    private int id;
    private double score;
}

重新访问:http://localhost:8080/student/1

获得结果: {“id”:1,”score”:100}

这样就完成了自定义json解析,不需要在代码中手动的new对象去转化为json格式。

想一起交流或者有问题的朋友可以关注我的公众号,里面有群聊连接可以一起交流遇到的问题,如果失效可以后台回复我,每天会同步更新
博客连接 : AshinLee’s blog

公众号:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/AshinLi/article/details/79705526