LoginSignup
2
12

More than 5 years have passed since last update.

GSON使ってみる

Last updated at Posted at 2016-12-05

はじめに

GSONとはJSON文字列とJavaのオブジェクトを相互に変換(シリアライズ/デシリアライズ)するためのライブラリです。Google製。

Androidプロジェクトに導入

build.gradleに書きましょう
書いたらSync Project with Gradle Filesして完了。

build.gradle
dependencies {
    compile 'com.google.code.gson:gson:2.4'
}

Modelクラス定義

こんな感じで。
ここらへん確認しとけばいいでしょう。
変数名とJsonのキー名が完全一致している場合、@SerializedNameアノテーションは指定しなくても問題ないです。
SubModel.mDataみたいに一致しないときはJsonのキー名を指定してあげましょう。

GsonSampleModel
import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

class GsonSampleModel {
    int num;
    float floatNum;
    String data;
    List<String> dataList;
    ArrayList<String> dataArrayList;
    HashMap<String, String> dataHashMap;
    InnerModel subModel;
    List<InnerModel> innerModelList;
    ArrayList<InnerModel> innerModelArrayList;
    HashMap<String, InnerModel> innerModelHashMap;

    class InnerModel {
        @SerializedName("data")
        String mData;

        InnerModel(String data) {
            mData = data;
        }
    }
}

使い方

お手軽ですねー

GsonTest
import com.google.gson.Gson;

public static void main(String[] args) {
    // Model生成
    GsonSampleModel model = createModel();

    // Gson初期化
    Gson gson = new Gson();

    // GsonSampleModel→Stringへの変換(シリアライズ)
    String json = gson.toJson(model);
    Log.d("sample", json);

    // String→GsonSampleModelへの変換(デシリアライズ)
    GsonSampleModel deserializedModel = gson.fromJson(json, GsonSampleModel.class);
    Log.d("sample", deserializedModel.toString());
}

private GsonSampleModel createModel() {
    GsonSampleModel model = new GsonSampleModel();
    model.num = 100;
    model.floatNum = 100.11f;
    model.data = "データ";
    model.dataList = Arrays.asList("でーた1", "でーた2");
    model.dataArrayList = new ArrayList<>(model.dataList);
    model.dataHashMap = new HashMap<>();
    model.dataHashMap.put("1", "でーた1");
    model.dataHashMap.put("2", "でーた2");
    model.subModel = new GsonSampleModel().new InnerModel("いんなー");
    model.innerModelList = Arrays.asList(
            new GsonSampleModel().new InnerModel("いんなー1"),
            new GsonSampleModel().new InnerModel("いんなー2")
    );
    model.innerModelArrayList = new ArrayList<>(model.innerModelList);
    model.innerModelHashMap = new HashMap<>();
    model.innerModelHashMap.put("1", new GsonSampleModel().new InnerModel("いんなー1"));
    model.innerModelHashMap.put("2", new GsonSampleModel().new InnerModel("いんなー2"));

    return model;
}
2
12
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
2
12