使用Moshi将字符串date从json转换为Date对象 [英] Turn string date from json to a Date object with Moshi

查看:259
本文介绍了使用Moshi将字符串date从json转换为Date对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与Gson一起做

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

并将其传递给改造生成器,Gson会为您创建一个Date对象,是否有某种方法可以让Moshi在kotlin类中做到这一点?

and pass it to the retrofit builder and Gson would make a Date object for you, Is there some way to get Moshi to do this too in a kotlin class?

推荐答案

(如果您想使用标准的ISO-8601/RFC 3339日期适配器,则可以使用内置适配器:

If you’d like to use a standard ISO-8601/RFC 3339 date adapter (you probably do) then you can use the built-in adapter:

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依赖项才能使其正常工作:

You’ll need this Maven dependency to make that work:

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

如果您想使用自定义格式(您可能不想使用),则可以使用更多代码.编写一个接受日期并将其格式化为字符串的方法,并编写另一种接受字符串并将其解析为日期的方法.

If you want to use a custom format (you probably don’t), there’s more code. Write a method that accepts a date and formats it to a string, and another method that accepts a string and parses it as a date.

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配置时区.

You need to remember to use synchronized because SimpleDateFormat is not thread-safe. Also you need to configure a time zone for the SimpleDateFormat.

这篇关于使用Moshi将字符串date从json转换为Date对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆