在测试过程中,发现了Date类型,在两个框架里解析是不同的方式 。
- fastjson:Date直接解析为Unix
- Gson:直接序列化为标准格式Date

文章插图
导致了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 。
文章插图
采用类似下文的解决方案(添加Gson适配器):
http://yuyublog.top/2018/09/03/springboot%E5%BC%95%E5%85%A5swagger/
- GsonSwaggerConfig.java
@Configurationpublic class GsonSwaggerConfig { //设置swagger支持gson @Bean public IGsonHttpMessageConverter IGsonHttpMessageConverter() { return new IGsonHttpMessageConverter(); }}- IGsonHttpMessageConverter.java
public class IGsonHttpMessageConverter extends GsonHttpMessageConverter { public IGsonHttpMessageConverter() { //自定义Gson适配器 super.setGson(new GsonBuilder() .registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter()) .serializeNulls()//空值也参与序列化 .create()); }}- 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作为入参异常有时候,我们会在入参使用类似:
推荐阅读
- 为啥阿里巴巴不建议MySQL使用Text类型?
- 淘宝直播三大核心技术揭秘
- 揭秘阿里巴巴的客群画像
- 阿里认证的证书有哪些 阿里巴巴企业认证怎么认证
- 阿里巴巴认证不通过是什么原因 阿里云认证证书有用吗
- 淘宝开店怎么发货 阿里巴巴铺货到淘宝店铺怎么发货
- 淘宝生意参谋怎么看同行转化率 阿里巴巴生意参谋怎么看同行数据
- 淘宝进货渠道除了阿里巴巴还有什么 淘宝的进货渠道
- 淘宝店铺关联代码在哪里找 阿里巴巴店铺关联快递的代码在哪
- 在阿里巴巴一件代发怎么发货 阿里巴巴怎么一件代发货
