java 谷歌 GSON 嵌套 HashMaps 反序列化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14358350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:59:50  来源:igfitidea点击:

Google GSON nested HashMaps deserialization

javajsongson

提问by ilya.stmn

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

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

        }
    }
  }
 }

And my pojo's

还有我的 pojo

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?

有什么建议?

回答by eugen

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.

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