Google GSON嵌套了HashMaps反序列化

时间:2013-01-16 12:20:53

标签: java json gson

在我目前的项目中,我在android中使用了GSON库,我遇到了嵌套地图反序列化的问题。这就是初始json的样子

 {

"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",

        }
    }
  }
 }

我的pojo's

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

和花类

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

但是当我尝试反序列化这个对象时,我可以访问嵌套的哈希映射,示例代码是

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();
       }

    }
 }

有什么建议吗?

1 个答案:

答案 0 :(得分:29)

gson.fromJson(br, HashMap.class);告诉Gson您要反序列化为未知值类型的Map。您可能想要指定Map<String,Category>.class之类的东西,但是您无法在Java中执行此操作,因此解决方案是在Gson中使用他们所谓的TypeToken。

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