ilya.stmn
ilya.stmn

Reputation: 1624

Google GSON nested HashMaps deserialization

In my current project i use GSON library in android, and i've faced a problem of nested Maps deserializtion. This is how initial json looks like

 {

"5":{
    "id":5,
    "name":"initial name",
    "image_url":"uploads/71d44b5247cc1a7c56e62fa51ca91d9b.png",
    "status":"1",
    "flowers":{
        "7":{
            "id":7,
            "category_id":"5",
            "name":"test",
            "description":"some description",
            "price":"1000",
            "image_url":"uploads/test.png",
            "status":"1",
            "color":"red",

        }
    }
  }
 }

And my pojo's

class Category {
long id;
String name;
String image_url;
HashMap<String,Flower> flowers;
}

And Flower class

class Flower {
long id;
String category_id;
String name;
String description;
String price;
String image_url;
String status;
}

But when i try to deserialize this objects, i can access nested hashmaps, the example code is

public class TestJson {
public static void main(String[] args) {
  Gson gson = new Gson();
    try {
    BufferedReader br = new BufferedReader(
        new FileReader("2.txt"));
    HashMap<String,Category> map = gson.fromJson(br, HashMap.class);
    Collection<Category> asd = map.values();
            System.out.println(map.values());

       } catch (IOException e) {
        e.printStackTrace();
       }

    }
 }

Any suggestions?

Upvotes: 14

Views: 14701

Answers (1)

eugen
eugen

Reputation: 5916

This gson.fromJson(br, HashMap.class); tells to Gson that you want to deserialize to a Map of unknown value type. You would be tempted to specifiy something like Map<String,Category>.class, but you can not do this in Java so the solution is to use what they called TypeToken in Gson.

Map<String, Category> categoryMap = gson.fromJson(br, new TypeToken<Map<String, Category>>(){}.getType());

Upvotes: 33

Related Questions