[英]gson JsonSyntaxException to Java Date from .net DateTime
How can I convert C#'s DateTime format from gson to Java Date? 如何将C#的DateTime格式从gson转换为Java Date? In gson which setDateFormat is correct?
在gson中,哪个setDateFormat是正确的? C#
C#
DateTime time = DateTime.Now;
JSON JSON
{
"date_time": "2015-04-24T09:22:08.6964069+08:00"
}
Android 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. 如果您不能使用通常用于
ISO 8601 time zone
的X
模式符号,则由于时区中的冒号,因此您无法使用此日期格式。 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
处理,从中删除冒号(例如replaceAll(String)
,然后使用RFC 822 time zone
(模式符号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 . SimpleDateFormat提供了基础约定,如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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.