前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring boot之JSON(二)

Spring boot之JSON(二)

作者头像
楠楠
发布2018-09-11 11:49:35
7880
发布2018-09-11 11:49:35
举报
文章被收录于专栏:郭少华郭少华

Spring boot 返回json数据

编写实体类Student

代码语言:javascript
复制
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
/**
 * 这是一个测试实体类
 */
public class Student {
    private String id;
    private String name;
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date   birthdate;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthdate() {
        return birthdate;
    }

    public void setBirthdate(Date birthdate) {
        this.birthdate = birthdate;
    }
}

Springboot默认使用jackson解析json日期类型序列化格式需要在时间属性上加 @JsonFormat(timezone="GMT+8",pattern="yyyy-MM-dd") 是将String转换成Date,一般前台给后台传值时用 @DateTimeFormat(pattern="yyyy-MM-dd") 是将Date转换成String 一般后台传值给前台时使用

编写getStudent方法

代码语言:javascript
复制
package com.springboot.backstage.controller;
import com.springboot.backstage.entity.Student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

//SpringBoot提供了refult风格
// @RestController相当于@Controller和@ResponseBody
@RestController
public class HellController {

 
    /**
     * Springbootm默认使用jackson解析json
     * @return
     */
    @RequestMapping("/getStudent")
    public Student getStudent(){
        Student student =new Student();
        student.setId("1");
        student.setName("张三");
        student.setBirthdate(new Date());
        return student;
    }

}

运行main函数测试

代码语言:javascript
复制
@SpringBootApplication
public class SpringBootApp extends WebMvcConfigurerAdapter {
  public static void main(String[] args) {
       SpringApplication.run(SpringBootApp.class,args);
    }
}

image.png

这里推荐一个google浏览器插件(JSON Viewer)可以更清楚的展示json数据

Spring boot使用FastJson解析JSON数据

引入fastjson依赖库

代码语言:javascript
复制
 <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.41</version>
 </dependency>

这里要说下很重要的话,官方文档说的1.2.10以后,会有两个方法支持HttpMessageconvert,一个是FastJsonHttpMessageConverter,支持4.2以下的版本,一个是FastJsonHttpMessageConverter4支持4.2以上的版本,具体有什么区别暂时没有深入研究。这里也就是说:低版本的就不支持了,所以这里最低要求就是1.2.10+。

第一种方法

第一种方法就是: (1)启动类继承extends WebMvcConfigurerAdapter (2)覆盖方法configureMessageConverters

代码
代码语言:javascript
复制
package com.springboot.backstage.controller;
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.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
public class SpringBootApp extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        //1.需要先定义一个convert消息转换的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //2.添加fastJson的配置信息,比如:要格式化返回的json数据
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat
        );
        //3.处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        //4.在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastConverter);
    }
 public static void main(String[] args) {
       SpringApplication.run(SpringBootApp.class,args);
    }
}
测试

把Student类的date对象改成能接收fastjson返回的date如果被格式化说明已经使用fastjson解析 @JSONField(format = "yyyy-MM-dd") fastjson另一个参数可以让属性不参与序列化 @JSONField(serialize=false)

代码语言:javascript
复制
package com.springboot.backstage.entity;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;

/**
 * 这是一个测试实体类
 */
public class Student {
    private String id;
    private String name;
    @JSONField(format = "yyyy-MM-dd")
    private Date   birthdate;
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthdate() {
        return birthdate;
    }

    public void setBirthdate(Date birthdate) {
        this.birthdate = birthdate;
    }
}

image.png

第二种方法

在这里使用@Bean注入FastJsonHttpMessageConverter

代码
代码语言:javascript
复制
package com.springboot.backstage.controller;
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.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
public class SpringBootApp  {
    /**
     * 在这里使用@Bean注入FastJsonHttpMessageConverter
     * @return
     */
    @Bean
    public  HttpMessageConverters fastJsonHttpMessageConverter(){
        //1.需要先定义一个convert消息转换的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //2.添加fastJson的配置信息,比如:要格式化返回的json数据
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        //3.处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);

        //4.在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);

        HttpMessageConverter<?> converter = fastConverter;
        return new HttpMessageConverters(converter);


    }

    public static void main(String[] args) {
       SpringApplication.run(SpringBootApp.class,args);
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.11.30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Spring boot 返回json数据
    • 编写实体类Student
      • 编写getStudent方法
        • 运行main函数测试
        • Spring boot使用FastJson解析JSON数据
          • 引入fastjson依赖库
            • 第一种方法
              • 代码
              • 测试
            • 第二种方法
              • 代码
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档