【问题标题】:GSON Date Format - Handling null date in the JSON parsingGSON 日期格式 - 在 JSON 解析中处理空日期
【发布时间】:2026-01-17 16:40:02
【问题描述】:

我正在尝试将 JSON 转换为自定义 bean。但是当 JSON 中的日期值为 null 时,我会遇到问题。

有效的 JSON 字符串,它被转换没有任何问题,因为 from 和 to date 都有值:

{"title":"1201 Box Title 1","fromdate":"01/02/2017","description":"1201 Box Title 1","todate":"01/26/2017"}

错误的 JSON 字符串:起始日期为空

{"title":"1201 Box Title 1","fromdate":"","description":"1201 Box Title 1","todate":"01/26/2017"}

用于初始化的Java代码:

 Gson testGson = new GsonBuilder().setDateFormat("MM/dd/yyyy").create();
 MyTestBean myTestBean = testGson.fromJson(jsonString, MyTestBean.class);

在 bean fromdate 和 todate 属性中声明为“Date”数据类型

错误堆栈跟踪:

Exception in thread "main" com.google.gson.JsonSyntaxException: 
at com.google.gson.DefaultDateTypeAdapter.deserializeToDate(DefaultDateTypeAdapter.java:107)
at com.google.gson.DefaultDateTypeAdapter.deserialize(DefaultDateTypeAdapter.java:82)
at com.google.gson.DefaultDateTypeAdapter.deserialize(DefaultDateTypeAdapter.java:35)
at com.google.gson.TreeTypeAdapter.read(TreeTypeAdapter.java:59)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
at com.google.gson.Gson.fromJson(Gson.java:755)
at com.google.gson.Gson.fromJson(Gson.java:721)
at com.google.gson.Gson.fromJson(Gson.java:670)
at com.google.gson.Gson.fromJson(Gson.java:642)
at JSONConverter.main(JSONConverter.java:15)
Caused by: java.text.ParseException: Unparseable date: ""
    at java.text.DateFormat.parse(DateFormat.java:366)
    at com.google.gson.DefaultDateTypeAdapter.deserializeToDate(DefaultDateTypeAdapter.java:105)
    ... 10 more

谁能告诉我如何以正确的方式处理这个问题。

我试图解决这个问题的一种方法如下,但想知道 GSON 本身是否有任何内置选项来处理空​​日期:

  1. 将 bean 中的起止日期声明为字符串数据类型
  2. 在 bean 中编写一个自定义 getter 方法,该方法将在返回日期之前进行解析,该日期将由使用此 bean 的代码使用

【问题讨论】:

  • 你有一个空字符串,不是null
  • 这是否意味着如果我们通过 null GSON 会处理这个问题?
  • 可能不会。您可能会得到 NullPointerException 而不是 ParseException
  • 感谢 cricket_007,传递 null 解决了这个问题。正在工作的 JSON 字符串如下: {"title":"1201 Box Title 1","fromdate":null,"description":"1201 Box Title 1","todate":"01/26/2017"}在 bean 中,它设置为 null 我们需要在使用该 bean 值时进行处理。 UI 还需要进行更改以将其作为 null 而不是空字符串传递。

标签: java json date gson


【解决方案1】:

整合 cmets 来自我的问题,并从这些 cmets 中放置答案:

在没有任何解析问题的情况下运行良好的 JSON 字符串是:

{"title":"1201 Box Title 1","fromdate":null,"description":"1201 Box Title 1","todate":"01/26/2017"}

在构造 JSON 以传递 null 而不是空字符串的 JS 中添加所需条件后,修复了该问题。

感谢@cricket_007 指出需要解决的问题。

【讨论】: