Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google GSON nested HashMaps deserialization

Tags:

java

json

gson

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?

like image 528
ilya.stmn Avatar asked Jan 16 '13 12:01

ilya.stmn


People also ask

Is GSON toJson thread safe?

Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple threads.

Does Gson ignore extra fields?

As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.

What does GSON toJson do?

Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.


1 Answers

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());
like image 161
eugen Avatar answered Oct 02 '22 14:10

eugen