如何转换Jackson和Gson之间的日期?

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

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

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

您需要为日期注册自己的反序列化程序。

我在下面创建了一个小例子,其中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() { @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()); } } 

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

另外:jackson在Android上工作正常,如果你不介意在Gson上使用它。