使用Moshi将json中的字符串日期转换为Date对象

与Gson你会做到这一点

Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm") .create(); 

并把它传递给改造者,Gson会为你制作一个Date对象,有没有办法让Moshi在Kotlin类中也这样做?

如果您想使用标准的ISO-8601 / RFC 3339数据适配器(您可能会这样做),那么您可以使用内置的适配器:

 Moshi moshi = new Moshi.Builder() .add(Date.class, new Rfc3339DateJsonAdapter().nullSafe()) .build(); JsonAdapter<Date> dateAdapter = moshi.adapter(Date.class); assertThat(dateAdapter.fromJson("\"1985-04-12T23:20:50.52Z\"")) .isEqualTo(newDate(1985, 4, 12, 23, 20, 50, 520, 0)); 

你需要这个Maven依赖来完成这个工作:

 <dependency> <groupId>com.squareup.moshi</groupId> <artifactId>moshi-adapters</artifactId> <version>1.5.0</version> </dependency> 

如果你想使用自定义格式(你可能不这样做),那么还有更多的代码。 编写一个接受日期并将其格式化为字符串的方法,另一种接受字符串并将其解析为日期的方法。

 Object customDateAdapter = new Object() { final DateFormat dateFormat; { dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); } @ToJson synchronized String dateToJson(Date d) { return dateFormat.format(d); } @FromJson synchronized Date dateToJson(String s) throws ParseException { return dateFormat.parse(s); } }; Moshi moshi = new Moshi.Builder() .add(customDateAdapter) .build(); JsonAdapter<Date> dateAdapter = moshi.adapter(Date.class); assertThat(dateAdapter.fromJson("\"1985-04-12T23:20\"")) .isEqualTo(newDate(1985, 4, 12, 23, 20, 0, 0, 0)); 

您需要记住使用synchronized因为SimpleDateFormat不是线程安全的。 你也需要为SimpleDateFormat配置一个时区。