GSON嵌套HashMaps反序列化

GSON嵌套HashMaps反序列化

本文介绍了Google GSON嵌套HashMaps反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我当前的项目中,我在android中使用GSON库,并且遇到嵌套Maps反序列化问题。这是初始json的样子

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

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


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?

解决方案

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

这篇关于Google GSON嵌套HashMaps反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:25