gpt4 book ai didi

java - Google GSON 嵌套 HashMaps 反序列化

转载 作者:太空狗 更新时间:2023-10-29 23:02:43 31 4
gpt4 key购买 nike

在我当前的项目中,我在 android 中使用 GSON 库,并且我遇到了嵌套 map 反序列化的问题。这是初始 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 的

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

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

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

}
}

有什么建议吗?

最佳答案

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

关于java - Google GSON 嵌套 HashMaps 反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14358350/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com