【问题标题】:gson fails to parse using GsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")gson 无法使用 GsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") 解析
【发布时间】:2014-10-16 18:52:15
【问题描述】:

我从服务器得到这个字符串:

[
 {
  "title":"spoil the ones u love today",
  "startDateTime":"2014-08-10T20:10:36.7158Z"
 },
 {
  "title":"home made patisserie",
  "startDateTime":"2014-08-10T20:08:45.0218Z"
 }
]

我尝试将它解析为一个对象

    public class Offer implements Serializable {
        public String title;
        public Date startDateTime;
    }

Type collectionType = new TypeToken<ArrayList<Offer>>() {}.getType();

mOffersList.addAll((Collection<? extends Offer>) gson.fromJson(result, collectionType));

但是当我将“startDate”定义为日期时

我从 gson 取回的集合是空的

当我将“startDate”定义为字符串时

集合已正确填充。

我想更改它的日期格式。这就是为什么我更喜欢将它保存为 Date 对象。

我试过了

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

然而 Gson 无法将服务器的字符串解析成

Date startDateTimemOffersList 没有添加任何内容,并且它保持为空。

我做错了什么?

【问题讨论】:

  • 你有没有试过最后用'Z'代替Z

标签: java json date gson simpledateformat


【解决方案1】:

仅设置所需的 DateFormat 是不够的。

您需要定义 com.google.gson.JsonDeserializer 的实现。例如。

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class DateDeserializer implements JsonDeserializer<Date> {

  @Override
  public Date deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
      String date = element.getAsString();

      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
      format.setTimeZone(TimeZone.getTimeZone("GMT"));

      try {
          return format.parse(date);
      } catch (ParseException exp) {
          System.err.println("Failed to parse Date:", exp);
          return null;
      }
   }
}

然后注册上面的反序列化器:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());

【讨论】:

  • 但是 gson 如何知道何时解析 date-json?
  • 那么为什么 gsonBuilder 存在 setDateFormat()?不作为一种简单的实现的捷径?
  • 当我运行您的代码时,它会抛出“java.text.ParseException: Unparseable date: "2014-08-10T20:10:36.7158Z" (at offset 23)"。请在末尾更改为“Z”而不是 Z
  • 虽然有效。我会很感激在 cmets 中回答我的上述问题
  • 感谢您在 cmets 1、2 中回答我上述问题
猜你喜欢
  • 2013-12-08
  • 2022-01-20
  • 1970-01-01
  • 2013-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
  • 1970-01-01
相关资源
最近更新 更多