LoginSignup
5
11

More than 5 years have passed since last update.

GsonでJSONからHashMapを作る

Posted at

GsonでHashMapも使って高速開発を更に爆速に

今やAPI連携のAndroidアプリの高速開発に欠かせないGson。WebAPIから持ってきたJSONを一瞬でModelクラスに入れて……の手順にもう1テクニック。GsonはHashMapにも変換することができる。

AndroidTestCaseのテストコードをそのまま。

XxxTest.java
 public void test_JSON2HashMapByGson () throws Exception{
        String json = "{\"apple\":3, \"orange\":2}";
        Gson gson = new Gson();
        Type listType = new TypeToken<HashMap<String, Integer>>() { }. getType();
        HashMap<String, Integer> fruitMap = gson.fromJson(json, listType);

        assertEquals((int) fruitMap.get("apple"), 3);
        assertEquals((int) fruitMap.get("orange"), 2);

        json = "{\"fruit\":{\"apple\":3, \"orange\":2}}";
        listType = new TypeToken<Fruit>() { }. getType();
        Fruit fruitObject = gson.fromJson(json, listType);

        fruitObject.fruitMap.get("apple");
        assertEquals((int) fruitObject.fruitMap.get("apple"), 3);
        assertEquals((int) fruitObject.fruitMap.get("orange"), 2);

    }
Fruit.java
    class Fruit {
        @SerializedName("fruit")
        private HashMap<String, Integer> fruitMap;
    }
5
11
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
5
11