写在前面
java开发中有许多库为我们的工作带来了便捷性,但是库非常非常多,比如json就有Gson,fastjson,jackson等。其实我个人感觉,使用哪个库都无所谓,只要能满足需求,把功能做出来就行了。当然,公司有规定,有性能要求的另算。
我想写一个系列,说不算是教程,仅仅是为了总结,方便自己平时开发查阅。毕竟感觉查文档很耗时间,最终想形成的一个效果是方便自己快速查阅,并且有相应的使用例子。如标题所示,二八法则为规则。精炼出最常用最常用的功能,实现快速查阅。文章不会像是写一个教程一样,从介绍开始写。
fastjson
官方文档地址为:点击我
常用API
- 序列化一个对象为JSON字符串
String jsonString = JSON.toJSONString(object);
- 反序列化JSON字符串为对象
Object object = JSON.parseObject(jsonString,Object.class)
List<Object> objectList = JSON.parseArray(jsonStringArray,Object.class)
- 日期格式处理 直接在对象上对日期类型进行格式化处理
public static class Model{
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private java.util.Date time;
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private java.sql.Date time2
}
- JSON.writeJSONString参数说明
| 参数 | 说明 |
|---|---|
| QuoteFieldNames | 使用引号 |
| UseSingleQuotes | 使用单引号 |
| WriteMapNullValue | 输出map的null值 |
| WriteEnumUsingToString | 枚举属性输出toString的结果 |
| WriteEnumUsingName | 枚举数据输出name |
| UseISO8601DateFormat | 使用日期格式 |
| WriteNullListAsEmpty | list为空则输出[] |
| WriteNullStringAsEmpty | String为空则输出"" |
| WriteNullNumberAsZero | Number类型为空则输出0 |
| WriteNullBooleanAsFalse | Boolen类型为空则输出false |
| SkipTransientField | |
| SortField | 排序字段 |
| PrettyFormat | 格式化JSON缩进 |
| WriteClassName | 输出类名 |
| WriteSlashAsSpecial | 对反斜杠"/"转义 |
JSON.toJSONString(word,SerializeFeature.PrettyFormat,SerializeFeature.WriteMapNullValue,SerializeFeature.WriteNullStringAsEmpty,SerializeFeature.WriteNullListAsEmpty)
- @Annotation注解使用
@JSONField(name = "ID")
public int getId(){return id;}
@JSONField(serialize=false) //不序列化
public Date date1;
@JSONField(Deserialize=false) //不反序列化
public Date date3;
@JSONField(ordinal=1) //排序1
private int f1;
自定义序列化与反序列化
- 子定义序列化
当配置无法满足自定义序列化时,使用
ObjectSerializer接口
(1) 实现ObjectSerializer
public class CharacterSerializer implements ObjectSerializer{
public void write(JSONSerializer serializer,
Object object,
Object fieldName,
Type fieldType
int features) throws IOException{
SerializeWrite out = serializer.out;
Character value = (Character)object;
if (value == null) {
out.writeString("");
return;
}
char c = value.charValue();
if (c == 0) {
out.writeString("\u0000");
}else {
out.writeString(value.toString());
}
}
}
(2) 注册ObjectSerializer
SerializeConfig.getGlobalInstance().put(Character.calss,new CharacterSerializer())
与SpringBoot整合
- (1)依赖配置
从starter-web中先排除spring-boot-starter-json
<!-- Spring Boot web启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
- 2.配置fastjson
配置fastjson一般有两种方式
(1)注入bean
在启动类Application里添加public HttpMessageConverters fastJsonHttpMessageConverters()
package com.songguoliang.springboot;
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.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import tk.mybatis.spring.annotation.MapperScan;
/**
* @Description
* @Author sgl
* @Date 2018-05-02 14:51
*/
@SpringBootApplication
@MapperScan("com.songguoliang.springboot.mapper")
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
/**
* 覆盖方法configureMessageConverters,使用fastJson
* @return
*/
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
//1、定义一个convert转换消息的对象
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//2、添加fastjson的配置信息
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
//3、在convert中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
//4、将convert添加到converters中
HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter);
}
}
(2)重写configureMessageConverters()
启动类继承WebMvcConfigureAdapter并重写configure MessageConverters,注意,在springboot2.x中已经变为WebMvcConfiger
package com.songguoliang.springboot;
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.WebMvcConfigurer;
import tk.mybatis.spring.annotation.MapperScan;
import java.util.List;
/**
* @Description
* @Author sgl
* @Date 2018-05-02 14:51
*/
@SpringBootApplication
@MapperScan("com.songguoliang.springboot.mapper")
public class Application implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//1、定义一个convert转换消息的对象
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//2、添加fastjson的配置信息
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
//3、在convert中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
//4、将convert添加到converters中
converters.add(fastConverter);
}
}