java gson 无法使用 GsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") 解析

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25455123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:04:11  来源:igfitidea点击:

gson fails to parse using GsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")

javajsondategsonsimpledateformat

提问by Elad Benda2

I get this string from the server:

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

[
 {
  "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"
 }
]

and I try to parse it an object

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

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

but when I define "startDate" as a Date

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

the collection I get back from gson is empty

我从 gson 回来的收藏是空的

When i define "startDate" as a String

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

the collection is filled correctly.

该集合已正确填充。

I want to change its date format. That's why I prefer saving it as a Date object.

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

I have tried

我努力了

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

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

and yet Gson fails to parse the server's string into

但是 Gson 无法将服务器的字符串解析为

Date startDateTime. Nothing is added to the mOffersListand it stays empty.

Date startDateTime. 没有添加任何内容mOffersList并且它保持为空。

What am I doing wrong?

我究竟做错了什么?

回答by Vaibhav Raj

Only setting the required DateFormat is not sufficient.

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

You need to define an implementation of com.google.gson.JsonDeserializer. For ex.

您需要定义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;
      }
   }
}

and then register the above deserializer:

然后注册上面的解串器:

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