简体   繁体   中英

gson JsonSyntaxException to Java Date from .net DateTime

How can I convert C#'s DateTime format from gson to Java Date? In gson which setDateFormat is correct? C#

DateTime time = DateTime.Now;

JSON

{
  "date_time": "2015-04-24T09:22:08.6964069+08:00"
}

Android

private Date date_time;

Gson gson=  new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
gson.fromJson(resultString, objectClass);

E/AndroidRuntime(24671): Caused by: com.google.gson.JsonSyntaxException: 2015-04-24T16:20:08.3672729+08:00
E/AndroidRuntime(24671): Caused by: java.text.ParseException: Unparseable date: "2015-04-24T16:20:08.3672729+08:00"
E/AndroidRuntime(24671): at java.text.DateFormat.parse(DateFormat.java:626)
E/AndroidRuntime(24671): at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:79)

If you can't work with the X pattern symbol wich is typically used for the ISO 8601 time zone you cannot take care of this date format, because of the colon in the time zone. If you can make use of it, the pattern would look like this:

yyyy-MM-dd'T'HH:mm:ss.SSSSSSSXXX

A workaround would be to handle it as a String , remove the colon from it (eg replaceAll(String) and afterwards format it with the RFC 822 time zone (pattern symbol Z ):

String time = inputTime.replaceAll("([\\+\\-]\\d\\d):(\\d\\d)","$1$2"));
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZZZ");
Date myDate = format.parse(time);

Note: Because of the combination of milliseconds and time zone, you have to hardset the digitamount.

The SimpleDateFormat provides the underlying conventions, as stated in the GsonDoc .

对于DateTime.UtcNow ,模式将为"yyyy-MM-dd'T'HH:mm:ss.SSS" ,完整代码将为

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM