当我在Android中使用以下代码:
// convert JSON string to a List of Product objects
Type listType = new TypeToken<List<Product>>(){}.getType();
p = (List<Product>)new Gson().fromJson(json, listType);
它将会转换:
[{"$id":"1","ProductId":17,"Name":"Product1","Price":1.49,"Visible":true},
{"$id":"2","ProductId":19,"Name":"Product2","Price":3.89,"Visible":true},
{"$id":"3","ProductId":20,"Name":"Product3","Price":0.32,"Visible":true}]
使用具有字段int ProductId、String Name、double Price、boolean Visible以及其他一些字段的三个Product对象。
当我尝试使用包含C# DateTime的Orders进行相同操作时(JSON中),它会出现JsonSyntaxException: 2014-05-13T00:00:00。
所以,我的问题是:如何成功地将包含日期字符串(2014-05-13T00:00:00)的JSON字符串转换为Java.util.Date对象?
我尝试过以下方法:
// convert JSON string to a List of Order objects
Type listType = new TypeToken<List<Order>>(){}.getType();
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).create();
o = (List<Order>)gson.fromJson(json, listType);
并且
// convert JSON string to a List of Order objects
Type listType = new TypeToken<List<Order>>(){}.getType();
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL, DateFormat.FULL).create();
o = (List<Order>)gson.fromJson(json, listType);
但两者都没有起作用。
注意:我在Google上搜索了一下,大多数解决方案使用Java代码和API中的序列化程序和反序列化程序。但由于我无法修改从C# Web API发送的JSON,这对我来说不是一个选项。我只能在接收端(我的Android应用程序)添加东西。
附言:我可能有一个解决方案,尽管它需要额外的工作,并包含一个潜在减速的for循环:我将Order-class
中的Date Date
更改为String Date
(因此Gson解析将其放入该字符串字段),然后添加一个Date mDate
,在Gson
解析完整个JSON-array
订单后,我在一个循环中将Dates
解析成mDates
。不过,这种解决方案相当低效,如果有人知道如何在GsonBuilder内部完成它,我会非常感激。
感谢您提前提供的答复。