当我在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
,JsonSyntaxException : 2014-05-13T00:00:00
以及其他字段的Product对象。当我对Orders(在JSON中包含C#DateTime)进行尝试时,它失败并显示
JSON String
因此,我的问题是:如何将包含日期字符串(
2014-05-13T00:00:00
)的Java.util.Date
成功转换为serializers & deserializers
对象?我确实尝试了以下方法:
// 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中都使用
JSON
。但是,由于我无法修改从C#Web API发送的Date Date
,因此这不是我的选择。我只能在接收方的终端(我的Android应用)中添加内容。PS:我可能有一个解决方案,尽管这需要一些额外的工作并且包含可能会变慢的for循环:我将
Order-class
中的String Date
更改为Date mDate
(因此Gson解析会将其放在该String字段中),然后添加一个Gson
,并且在JSON-array
解析了订单的完整Dates
之后,我在for循环中将mDates
解析为ojit_code。尽管如此,该解决方案效率很低,因此,如果有人知道如何在GsonBuilder本身中做到这一点,我将不胜感激。预先感谢您的答复。
最佳答案
好的,我很接近,但是犯了一个小错误(而且很明显)。
代替:
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL, DateFormat.FULL).create();
我需要使用:
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
编辑:
现在,我也使用脱盐器,但仅在Android部分使用。我更改它的原因如下:
码:
try{
// Convert JSON-string to a List of Order objects
Type listType = new TypeToken<ArrayList<Order>>(){}.getType();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try{
return df.parse(json.getAsString());
}
catch(ParseException ex){
return null;
}
}
});
Gson dateGson = gsonBuilder.create();
orders = dateGson.fromJson(json, listType);
}
catch(JsonParseException ex){
ex.printStackTrace();
}