您的位置:首页 > 编程语言 > Java开发

【Spring-boot 】FastJson对json数据进行解析(类型转换)

2018-03-30 20:05 1061 查看

序列化

序列化就是指 把JavaBean对象转成JSON格式的字符串。将Map转成JSON
将List<Map>转成JSON。
自定义JavaBean User转成JSON。String objJson = JSON.toJSONString(Object object);

FastJSON可以直接对日期类型格式化,在缺省的情况下,FastJSON会将Date转成long。

FastJSON将java.util.Date转成long。
String dateJson = JSON.toJSONString(new Date());

System.out.println(dateJson); //1401370199040
String dateJson = JSON.toJSONString(new Date(), SerializerFeature.WriteDateUseDateFormat); //指定输出日期格式。
System.out.println(dateJson);  //"2014-05-29 21:36:24"
String listJson = JSON.toJSONString(list, SerializerFeature.UseSingleQuotes);//使用单引号
String listJson = JSON.toJSONString(list, true);  //显示的样子格式化
String listJson = JSON.toJSONString(list, SerializerFeature.PrettyFormat);
//显示的样子格式化


我们使用SpringBoot会直接将输出的数据转换成json格式。
但是我们需要将指定的数据转换成特定的格式呢?比如讲日期格式的转换显示。
主要有两种方式:
第一种:Spring boot的启动类继承  WebMvcConfigurerAdapter 重写configureMessageConverters方法
第二种:同样是继承WebMvcConfigurerAdapter 类,自己定义转换的方法,通过@Bean注解进行注入

(来操作一下)

步骤一:创建maven项目,在pom.xml中添加fastjson依赖 <!-- 引入fastjson依赖 -->
<dependency>
<groupId>com.alibaba </groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>步骤二:第一种方式(Spring boot的启动类继承  WebMvcConfigurerAdapter 重写configureMessageConverters方法)@SpringBootApplication
@ComponentScan("com.springboot")
@MapperScan("com.springboot.*") //扫描mybatis的配置信息
public class App extends WebMvcConfigurerAdapter{

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

@Override
public void configureMessageConverters( List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
//1.需要定义一个convert转换消息的对象
FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
//2.添加fashJson的配置消息,比如:是否要格式化返回的json数据
FastJsonConfig fastJsonConfig=new FastJsonConfig();
//3.在convert中添加配置信息
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
//4.将convert添加到converters当中
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}
第二种方式(继承WebMvcConfigurerAdapter 类,自己定义转换的方法,通过@Bean注解进行注入)@SpringBootApplication
@ComponentScan("com.springboot")
@MapperScan("com.springboot.*") //扫描mybatis的配置信息
public class App extends WebMvcConfigurerAdapter{

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

@Bean
public HttpMessageConverters fastJsonHttpMessageConverters(){
//1.需要定义一个convert转换消息的对象
FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
//2.添加fashJson的配置消息
FastJsonConfig fastJsonConfig=new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);

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

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

}
}

步骤三:直接在我们需要转换的数据的DTO类中添加@JSONField注解进行格式化

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: