Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to troubleshoot GSON time problem

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to troubleshoot GSON time problem". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to troubleshoot GSON time problem".

Problem description

Recently, an old project frequently encountered GSON deserialization time problems in the test environment. The error stack is as follows:

Exception in thread "main" com.google.gson.JsonSyntaxException: 2021-05-14 14:59:37 at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate (DateTypeAdapter.java:81) at com.google.gson.internal.bind.DateTypeAdapter.read (DateTypeAdapter.java:66) at com.google.gson.internal.bind.DateTypeAdapter.read (DateTypeAdapter.java:41) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read (ReflectiveTypeAdapterFactory.java) : 93) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read (ReflectiveTypeAdapterFactory.java:172) at com.google.gson.Gson.fromJson (Gson.java:795) at com.google.gson.Gson.fromJson (Gson.java:761) at com.google.gson.Gson.fromJson (Gson.java:710) at com.google.gson.Gson.fromJson (Gson.java:682) at com.gson .GsonDate.main (GsonDate.java:17) Caused by: java.text.ParseException: Unparseable date: "2021-05-14 14:59:37" at java.text.DateFormat.parse (DateFormat.java:366) at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate (DateTypeAdapter.java:79). 9 more

The error description is also very detailed, that is, when GSON deserializes a Json string, the entire Json deserialization fails because a certain time string cannot be deserialized.

Background description

Because of the large amount of data in this system, all the data from half a year ago will be archived to Hbase, and when archiving, the data in the database will be serialized into json format and then saved to Hbase. If the data in the recent half year will be queried directly in the database, if it is early data, Hbase will be queried, so the probability of occurrence is relatively low.

Local recurrence of problem analysis

To facilitate the analysis, copy the Json string locally, then reproduce it locally, and then analyze the problem. The Json string is relatively long. The following Json string is used instead:

{"date": "2021-05-14 14:59:37"}

Prepare the relevant code as follows:

Public class GsonDate {public static void main (String [] args) {String json = "{\" date\ ":\" 2021-05-14 14:59:37\ "}"; GsonDateBean date = new Gson () .fromJson (json, GsonDateBean.class); System.out.println (date);} @ Dataclass GsonDateBean {private Date date;}

The result of the execution is that the sequence can be reversed successfully without the above error. In order to find out the reason, we need to analyze the relevant source code of Gson time conversion.

Source code analysis

The source code for Gson time conversion is relatively simple. The part of the DateTypeAdapter code is as follows:

Private final DateFormat enUsFormat = DateFormat.getDateTimeInstance (DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US); private final DateFormat localFormat = DateFormat.getDateTimeInstance (DateFormat.DEFAULT, DateFormat.DEFAULT); private final DateFormat iso8601Format = buildIso8601Format (); private static DateFormat buildIso8601Format () {DateFormat iso8601Format = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); iso8601Format.setTimeZone (TimeZone.getTimeZone ("UTC")); return iso8601Format } private synchronized Date deserializeToDate (String json) {try {return localFormat.parse (json);} catch (ParseException ignored) {} try {return enUsFormat.parse (json);} catch (ParseException ignored) {} try {return iso8601Format.parse (json);} catch (ParseException e) {throw new JsonSyntaxException (json, e);}}

Gson prepares three DateFormat, namely: when localFormat,enUsFormat,iso8601Format; is converted, it is also converted in this order, and which one can be converted successfully will be returned directly. The above problems indicate that none of the three DateFormat has been converted successfully. Local debugging can be directly Debug in, and you can find that the conversion is successful directly using localFormat, and you can view each pattern separately.

LocalFormat:yyyy-M-d H:mm:ss

EnUsFormat:MMM d, yyyy h:mm:ss a

Iso8601Format:yyyy-MM-dd'T'HH:mm:ss'Z'

The above date format is completely in line with the yyyy-M-d H:mm:ss format, so it can be converted successfully. You can find that localFormat is actually related to the locale of the local system, so there will be inconsistencies between the local running results and the server running results.

Reappear again

You can set the locale to Locale.US directly through the code.

Public class GsonDate {public static void main (String [] args) {System.out.println ("default:" + Locale.getDefault ()); System.out.println ("reset locale: Locale.US"); Locale.setDefault (Locale.US); String json = "{\" date\ ":\" 2021-05-14 14:59:37\ "}" GsonDateBean date = new Gson () .fromJson (json, GsonDateBean.class); System.out.println (date);}}

Running the above code, there is the same anti-sequence time problem as the server:

Default: zh_CN reset locale: Locale.USException in thread "main" com.google.gson.JsonSyntaxException: 2021-05-14 14:59:37 at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate (DateTypeAdapter.java:81)

It can be found that our local environment is generally zh_CN, corresponding to Locale.CHINA.

Problem solving system configuration

The system locale can be changed directly, and liunx can be configured directly in / etc/sysconfig/i18n:

English version: LANG= "en_US.UTF-8" Chinese version: LANG= "zh_CN.UTF-8"

You can view the currently configured locale:

[root@Centos ~] # echo $LANGen_US.UTF-8 code implementation

You can set the default log conversion format for Gson:

Gson gson = new GsonBuilder () .setDateFormat ("yyyy-MM-dd HH:mm:ss") .create (); GsonDateBean date = gson.fromJson (json, GsonDateBean.class); extension

Similarly, if you use other Json serialization tools, such as fastjson, you can simply do a test:

Locale.setDefault (Locale.US); String json = "{\" date\ ":\" 2021-05-14 14:59:37\ "}"; String json2 = "{\" date\ ":\" 14:59:37 on 14 May 2021 "; JacksonDateBean date = JSON.parseObject (json, JacksonDateBean.class)

The result is that not only the yyyy-MM-dd HH:mm:ss format can be parsed, but also the year, month and day in Chinese can be parsed. If you look at the relevant source code, you can find that fastjson does not directly use DateFormat for date format conversion, but implements the ISO8601 standard and provides support for common date formats in China. You can directly check the scanISO8601DateIfMatch method in the source code JSONScanner. Another point to note is that the above GSON uses version 2.2.2, and the latest version 2.8.6 also provides support for the ISO8601 standard, which can be found in the ISO8601Utils class.

Thank you for your reading, the above is the content of "how to troubleshoot GSON time problem". After the study of this article, I believe you have a deeper understanding of how to troubleshoot GSON time problem, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report