Google GSON嵌套HashMaps反序列化 [英] Google GSON nested HashMaps deserialization
问题描述
在我当前的项目中,我在android中使用GSON库,并且遇到嵌套Maps反序列化问题。这是初始json的样子
{
pre>
5:{
ID:5,
name:初始名称,
image_url:uploads / 71d44b5247cc1a7c56e62fa51ca91d9b.png,
status:1,
花:{
7:{
id:7,
category_id:5,
name:test,
description:一些描述,
price:1000,
image_url:uploads / test.png,
status:1 ,
color:red,
}
}
}
}
我的pojo's
class类别{
长ID;
字符串名称;
String image_url;
HashMap< String,Flower>花卉;
}
和Flower类
class Flower {
long id;
String category_id;
字符串名称;
字符串描述;
弦乐价格;
String image_url;
字符串状态;
}
但是当我尝试反序列化这个对象时,我可以访问嵌套的hashmaps,示例代码是
public class TestJson {
public static void main(String [] args){
Gson gson = new Gson();
尝试{
BufferedReader br = new BufferedReader(
new FileReader(2.txt));
HashMap< String,Category> map = gson.fromJson(br,HashMap.class);
收藏<类别> 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 。地图< 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 likeMap<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反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文