【问题标题】:Android/Java - Gson parsing from JSON-string to Object(s) - Date issuesAndroid/Java - 从 JSON 字符串到对象的 Gson 解析 - 日期问题
【发布时间】:2014-07-01 06:16:10
【问题描述】:

当我在 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}]

三个 Product 对象的字段为 int ProductIdString Namedouble Priceboolean Visible,可能还有其他字段。


当我尝试对 Orders(在 JSON 中包含 C# DateTime)进行相同操作时,它会失败并显示 JsonSyntaxException : 2014-05-13T00:00:00

所以,我的问题是:如何将包含日期字符串 (2014-05-13T00:00:00) 的 JSON String 成功转换为 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 中都使用 serializers &amp; deserializers。但由于我无法修改从 C# Web API 发送的JSON,所以这不是我的选择。我只能在接收者端添加东西(我的 Android 应用)。

PS:我可能有一个解决方案,虽然它有点额外的工作并且包含一个可能会减慢 for 循环:我将我的 Order-class 中的 Date Date 更改为 String Date (因此 Gson 解析会将其放入那个字符串字段),然后添加一个Date mDate,在Gson解析了完整的订单JSON-array之后,我在for循环中将Dates解析为mDates。不过,这个解决方案还是很漂亮的效率低下,所以如果有人知道如何在 GsonBuilder 本身中做到这一点,我将不胜感激。

提前感谢您的回复。

【问题讨论】:

    标签: java android json date gson


    【解决方案1】:

    好的,我很接近,但犯了一个小(而且很明显)的错误..

    代替:

    Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL, DateFormat.FULL).create();
    

    我需要使用:

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

    编辑:

    我现在也使用解串器,但仅限于我的 Android 部分。我改的原因如下:

    • 当我有一个不同格式的日期或一个为空的日期时,我会在整个 JSON 上收到一个 JsonParseException,因此我的订单对象都没有被创建。
    • 现在我使用了这个序列化程序并且 Date 的格式似乎无效或为 null,它只会使 Order-object 中的 Date 为 null,但仍会使用结果 Order-list 转换所有内容。李>

    代码:

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-03
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多