GSON抛出解析空日期字段的异常 [英] GSON throws exception parsing empty Date field

查看:942
本文介绍了GSON抛出解析空日期字段的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用GSON对一些JSON进行反序列化。
JSON是:

  {
employee_id:297,
surname :Maynard,
givenname:Ron,
lastlogin:,

...



Employee对象有一个Date字段lastlogin:

  public class Employee {
private Integer employee_id;

私人字符串姓氏;

私人字符串givenname;

私人日期lastlogin;

我遇到的问题是,当lastlogin值没有填充时,它是一个空字符串JSON,所以GSON解析器抛出:

  java.text.ParseException:无法解析的日期:在java的
。在com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:79)上的text.DateFormat.parse(DateFormat.java:337)
;在com.google.gson.internal上为
。 bind.DateTypeAdapter.read(DateTypeAdapter.java:66)

通常的解决方法是什么?

  GsonBuilder gsonBuilder = new GsonBuilder(); 
DateFormat df = new SimpleDateFormat(yyyy-MM-dd HH:mm);
@Override
public Date deserialize(final JsonElement json,final Type typeOfT,final JsonDeserializationContext context)
throws JsonParseException {
try {
return df.parse(json.getAsString());
} catch(ParseException e){
return null;
}
}
});
Gson gson = gsonBuilder.create();

请参阅 https://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserializ


I'm using GSON to deserialise some JSON. The JSON is:

{
    "employee_id": 297,
    "surname": "Maynard",
    "givenname": "Ron",
    "lastlogin": "",

...

The Employee Object has a Date field lastlogin:

public class Employee {
private Integer employee_id;

private String surname;

private String givenname;

private Date lastlogin;

The problem I have is that when the lastlogin value isn't populated, it's an empty String in the JSON, so the GSON parser throws:

java.text.ParseException: Unparseable date: ""
at java.text.DateFormat.parse(DateFormat.java:337)
at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:79)
at com.google.gson.internal.bind.DateTypeAdapter.read(DateTypeAdapter.java:66)

What's the usual way around this?

解决方案

If you can't control the input (i.e. the JSon generating part) but know the format as it should be when not empty, you should just write an own deserializer that can handle empty values, like e.g.

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        @Override
        public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
                throws JsonParseException {
            try {
                return df.parse(json.getAsString());
            } catch (ParseException e) {
                return null;
            }
        }
    });
    Gson gson = gsonBuilder.create();

See https://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserializ

这篇关于GSON抛出解析空日期字段的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆