别了,阿里巴巴fastjson!企业项目迁移Gson全攻略( 四 )


在测试过程中,发现了Date类型,在两个框架里解析是不同的方式 。

  • fastjson:Date直接解析为Unix
  • Gson:直接序列化为标准格式Date

别了,阿里巴巴fastjson!企业项目迁移Gson全攻略

文章插图
 
导致了Gson在反序列化这个json的时候,直接报错,无法转换为Date 。
解决方案:
新建一个专门用于解析Date类型的类:
import com.google.gson.TypeAdapter;import com.google.gson.stream.JsonReader;import com.google.gson.stream.JsonWriter;import java.io.IOException;import java.util.Date;public class MyDateTypeAdapter extends TypeAdapter<Date> {    @Override    public void write(JsonWriter out, Date value) throws IOException {        if (value == null) {            out.nullValue();        } else {            out.value(value.getTime());        }    }    @Override    public Date read(JsonReader in) throws IOException {        if (in != null) {            return new Date(in.nextLong());        } else {            return null;        }    }}接着,在创建Gson时,把他放入作为Date的专用处理类:
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class,new MyDateTypeAdapter()).create();这样就可以让Gson将Date处理为Unix 。
当然,这只是为了兼容老的缓存,如果你觉得你的仓库没有这方面的顾虑,可以忽略这个问题 。
SpringBoot异常切换到Gson后,使用SpringBoot搭建的Web项目的接口直接请求不了了 。报错类似:
org.springframework.http.converter.HttpMessageNotWritableException因为SpringBoot默认的Mapper是Jackson解析,我们切换为了Gson作为返回对象后,Jackson解析不了了 。
解决方案:
application.properties里面添加:
#Preferred JSON mapper to use for HTTP message conversionspring.mvc.converters.preferred-json-mapper=gsonSwagger异常这个问题和上面的SpringBoot异常类似,是因为在SpringBoot中引入了Gson,导致 swagger 无法解析 json 。
别了,阿里巴巴fastjson!企业项目迁移Gson全攻略

文章插图
 
采用类似下文的解决方案(添加Gson适配器):
http://yuyublog.top/2018/09/03/springboot%E5%BC%95%E5%85%A5swagger/
  1. GsonSwaggerConfig.java
@Configurationpublic class GsonSwaggerConfig {    //设置swagger支持gson    @Bean    public IGsonHttpMessageConverter IGsonHttpMessageConverter() {        return new IGsonHttpMessageConverter();    }}
  1. IGsonHttpMessageConverter.java
public class IGsonHttpMessageConverter extends GsonHttpMessageConverter {    public IGsonHttpMessageConverter() {        //自定义Gson适配器        super.setGson(new GsonBuilder()                .registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter())                .serializeNulls()//空值也参与序列化                .create());    }}
  1. SpringfoxJsonToGsonAdapter.java
public class SpringfoxJsonToGsonAdapter implements JsonSerializer<Json> {    @Override    public JsonElement serialize(Json json, Type type, JsonSerializationContext jsonSerializationContext) {        return new JsonParser().parse(json.value());    }}@Mapping JsonObject作为入参异常有时候,我们会在入参使用类似:


推荐阅读