Json解析ライブラリMoshi

730 ワード

Moshiとは?
moshiはsquareチームがGitHubに発表したJson解析ライブラリGitHubです
使用法
  • まずはcompile:
  • compile 'com.squareup.moshi:moshi:1.2.0'
    
  • Json文字列のフォーマットによるエンティティの作成
  • class PersonList {
        Map list;
    }
    
    class Person {
        int age;
        Sex sex;
    }
    
    enum Sex {
        MAN,
        WOMAN
    }
    
  • moshiによるJson解析
  • String json = "xxxxxxx";
    
    Moshi moshi = new Moshi.Builder().build();
    JsonAdapter jsonAdapter = moshi.adapter(PersonList.class);
    
    try {
        PersonList personList = jsonAdapter.fromJson(json);
    } catch (Exception e) {
        Log.e("json parse error", "parsePersonList: ", e);
    }