• 问题复盘|在使用 Gson 时,报 Failed to parse date [““] 错误


    背景

    在使用 Gson 进行数据解析的时候,报了 Failed to parse date [“”] 错误

    原代码

    public void test() {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("name", "小红");
            jsonObject.addProperty("birthday", "");
            Gson gson = new GsonBuilder().create();
            User user = gson.fromJson(jsonObject, new TypeToken<User>() {
            }.getType());
            System.out.println("user is:\n" + user);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    报错

    com.google.gson.JsonSyntaxException: 
    	at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:87)
    	at com.google.gson.internal.bind.DateTypeAdapter.read(DateTypeAdapter.java:75)
    	at com.google.gson.internal.bind.DateTypeAdapter.read(DateTypeAdapter.java:46)
    	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:131)
    	at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:222)
    	at com.google.gson.Gson.fromJson(Gson.java:963)
    	at com.google.gson.Gson.fromJson(Gson.java:1034)
            ...
    Caused by: java.text.ParseException: Failed to parse date [""]: (java.lang.NumberFormatException)
    	at com.google.gson.internal.bind.util.ISO8601Utils.parse(ISO8601Utils.java:274)
    	at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:85)
    	... 34 more
    Caused by: java.lang.NumberFormatException: 
    	at com.google.gson.internal.bind.util.ISO8601Utils.parseInt(ISO8601Utils.java:302)
    	at com.google.gson.internal.bind.util.ISO8601Utils.parse(ISO8601Utils.java:129)
    	... 35 more
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    原因

    Gson 默认的 Date 类型转换器无法处理空字符串

    解决方法

    通过自定义 Gson 的 Date 类型转换器来解决这个问题

    Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            if (json.getAsJsonPrimitive().getAsString().equals("")) {
                return null;
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                return format.parse(json.getAsJsonPrimitive().getAsString());
            } catch (ParseException e) {
                throw new JsonParseException(e);
            }
        }
    }).create();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    新代码

    /**
     * user is:
     * User(id=null, name=小红, birthday=null)
     */
    public void test() {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("name", "小红");
            jsonObject.addProperty("birthday", "");
            Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                    if (json.getAsJsonPrimitive().getAsString().equals("")) {
                        return null;
                    }
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        return format.parse(json.getAsJsonPrimitive().getAsString());
                    } catch (ParseException e) {
                        throw new JsonParseException(e);
                    }
                }
            }).create();
            User user = gson.fromJson(jsonObject, new TypeToken<User>() {
            }.getType());
            System.out.println("user is:\n" + user);
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    我不是第一个踩此坑的,肯定也不会是最后一个踩此坑的,简单记录,等待有缘人

  • 相关阅读:
    日志库的设计与模块
    Golang 环境变量和项目结构
    qemu+docker在服务器上搭建linux内核调试环境
    LeetCode-剑指26-树的子结构
    基于Springboot+Vue实现前后端分离商城管理系统
    专访阿里云:AI 时代服务器操作系统洗牌在即,生态合作重构未来
    最长上升子序列Ⅱ
    java游戏制作-拼图游戏
    pwn调试环境搭建
    Linux命令:tr和xargs
  • 原文地址:https://blog.csdn.net/weixin_44435110/article/details/134430836