【问题标题】:How to convert a Date between Jackson and Gson?如何在杰克逊和 Gson 之间转换日期?
【发布时间】:2011-05-18 09:02:47
【问题描述】:

在我们的 Spring 配置的 REST 服务器中,我们使用 Jackson 将对象转换为 Json。该对象包含几个 java.util.Date 对象。

当我们尝试使用 Gson 的 fromJson 方法在 Android 设备上对其进行反序列化时,我们会得到一个“java.text.ParseException: Unparseable date”。自 1970 年以来,我们已尝试将日期序列化为与毫秒对应的时间戳,但得到了相同的异常。

Gson 是否可以配置为将时间戳格式的日期(例如 1291158000000)解析为 java.util.Date 对象?

【问题讨论】:

    标签: java json timestamp gson jackson


    【解决方案1】:

    您需要为 Dates 注册自己的反序列化器。

    我在下面创建了一个小示例,其中 JSON 字符串“23-11-2010 10:00:00”被反序列化为 Date 对象:

    import java.lang.reflect.Type;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    import com.google.gson.JsonDeserializationContext;
    import com.google.gson.JsonDeserializer;
    import com.google.gson.JsonElement;
    import com.google.gson.JsonParseException;
    
    
    public class Dummy {
        private Date date;
    
        /**
         * @param date the date to set
         */
        public void setDate(Date date) {
            this.date = date;
        }
    
        /**
         * @return the date
         */
        public Date getDate() {
            return date;
        }
    
        public static void main(String[] args) {
            GsonBuilder builder = new GsonBuilder();
            builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
    
                @Override
                public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                        throws JsonParseException {
    
                    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                    String date = json.getAsJsonPrimitive().getAsString();
                    try {
                        return format.parse(date);
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            Gson gson = builder.create();
            String s = "{\"date\":\"23-11-2010 10:00:00\"}";
            Dummy d = gson.fromJson(s, Dummy.class);
            System.out.println(d.getDate());
        }
    }
    

    【讨论】:

    • 这并不能真正回答问题,是吗?问题明确指出“时间戳格式的日期”
    【解决方案2】:

    关于 Jackson,您不仅可以在数字(时间戳)和文本序列化(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS)之间进行选择,还可以定义精确的 DateFormat 以用于文本变体(SerializationConfig.setDateFormat)。因此,如果 Gson 不支持 Jackson 默认使用的 ISO-8601 格式,您应该能够强制使用 Gson 识别的内容。

    另外:Jackson 在 Android 上运行良好,如果您不介意在 Gson 上使用它的话。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 2014-07-31
      相关资源
      最近更新 更多