本地调试代码是正常的, 没有报错, 但是一部署到环境上就报错.

通过pinpoint日志看到报了这个错. 

记一次Gson时间转化报:Caused by:java.text.ParseException:Failed to parse date:Invalid time zone indicator

 

仔细看了一下代码中gson的初始化直接是:

private static Gson gson = new Gson();

后来改成下面这样就可以了:

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

 

原因分析:

在Java中处理JSON格式的数据时,Google Gson是个不错的选择,用起来挺方便的,也有一定灵活性.

不过它在处理Date格式时有个小陷阱,在不同环境中部署时可能会遇到问题。 

Gson默认处理Date对象的序列化/反序列化是通过一个SimpleDateFormat对象来实现的, 

在不同的locale环境中,这样获取到的SimpleDateFormat的模式字符串会不一样,

为了避免使用Gson时遇到locale影响Date格式的问题,使用GsonBuilder来创建Gson对象,在创建过程中调用GsonBuilder.setDateFormat(格式)指定一个固定的格式即可。

 

相关文章:

  • 2021-08-19
  • 2021-12-31
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-28
  • 2022-12-23
  • 2021-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-24
  • 2022-12-23
  • 2021-06-10
  • 2022-12-23
相关资源
相似解决方案