Google GSON 嵌套 HashMaps 反序列化

2022-09-03 17:54:09

在我目前的项目中,我在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",

        }
    }
  }
 }

还有我的宝乔

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

这告诉 Gson 您要反序列化为未知值类型的 Map。你会很想指定类似的东西,但你不能在Java中这样做,所以解决方案是在Gson中使用他们所谓的TypeToken。gson.fromJson(br, HashMap.class);Map<String,Category>.class

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

答案 2