LoginSignup
0
0

More than 5 years have passed since last update.

jsonのDateがlong値の場合の、GsonBuilder対処法

Last updated at Posted at 2014-06-13

Android開発序盤で少し悩んだこと

  • APIからjson取ってきてgson使ってparse楽勝って思ってた
  • そしたら、APIのdateがtimestampなとこでエラった
console.log
com.google.gson.JsonSyntaxException: 1402654656000

( ´ー`)フゥー...GsonBuilderで簡単にformat定義できるかなって思ってた。
でも探したり試したりしたけど、なんか上手くいかない。。
良い方法あるのかもだけど。。

解決方法

  • 以下のように定義したら上手く変換してくれたヽ(`▽´)/
Gson gson = new GsonBuilder()
        .registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                return json == null ? null : new Date(json.getAsLong());
            }
        })
        .create();
  • もっと良い方法があるのかもしれないが、とりあえずよかたε-(´∀`*)ホッ

おまけ

  • ググったら解決したけど、fromJsonで
    beanじゃなくてListItem型になった問題の解決
// ListResponseはgenerics型のbean
ListResponseDto<ArticleDto> articles = gson.fromJson(body,
        new TypeToken<ListResponseDto<ArticleDto>>() {
        }.getType()
);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0