2015-09-04 71 views
0

我已经试过http://www.jsonschema2pojo.org/解决这个问题,但它没有奏效。我想创建一个JSON响应类此JSON格式:你如何为这个Json文件设置一个使用Gson的响应类?

{ 
      "Structure1": [ 
       [ 
        "StringValue1", 
        "StringValue2" 
       ], 
       [ 
        "StringValue1", 
        "StringValue2" 
       ] 
      ], 
      "Structure2": [ 
       [ 
        "StringValue1", 
        "StringValue2" 
       ] 
      ], 
      "Structure3": [ 
       [ 
        "StringValue1", 
        "StringValue2" 
       ] 
      ] 
     } 

这里是我当前类的样子:

public class Response { 
    private HashMap<String, ArrayList<ArrayList<String>>> map = new HashMap<String, ArrayList<ArrayList<String>>>(); 

    public HashMap<String, ArrayList<ArrayList<String>>> getMap() { 
     return map; 
    } 

    public void setFile11Txt(HashMap<String, ArrayList<ArrayList<String>>> map) { 
     this.map = map; 
    } 

} 

要分析我做

Response response = gson.fromJson(response, Response.class); 

的返回的地图最终是空的,我做错了什么?

+0

好友是你的回应字符串正确正在添加 – koutuk

+0

是的,这一点是好的 – noobcoder

+0

检查我张贴的答案 – koutuk

回答

1

我建议以下代码:

String jsonString = "{\n" + 
       "    \"Structure1\": [\n" + 
       "    [\n" + 
       "     \"StringValue1\",\n" + 
       "     \"StringValue2\"\n" + 
       "    ],\n" + 
       "    [\n" + 
       "     \"StringValue1\",\n" + 
       "     \"StringValue2\"\n" + 
       "    ]\n" + 
       "   ],\n" + 
       "   \"Structure2\": [\n" + 
       "    [\n" + 
       "     \"StringValue1\",\n" + 
       "     \"StringValue2\"\n" + 
       "    ]\n" + 
       "   ],\n" + 
       "   \"Structure3\": [\n" + 
       "    [\n" + 
       "     \"StringValue1\",\n" + 
       "     \"StringValue2\"\n" + 
       "    ]\n" + 
       "   ]\n" + 
       "  }"; 

Map<String, ArrayList<String>> myMap = gson.fromJson(jsonString, HashMap.class); 

Debug屏幕截图如下所示:

enter image description here

希望这会有所帮助!

+1

有一个未经检查的投从转换时原始的'HashMap'类型可能会导致错误。 myMap的类型是'Map >',但应该是'HashMap >>'。由于使用了原始类型,编译器在您尝试访问myMap之前不会捕获类型不匹配。例如,'列表 structure1List = myMap.get(“Structure1”)。get(0);'将无法编译。 – iagreen

+0

@iagreen:感谢您的评论。我同意你的意见 – BNK

+0

@noobcode:请接受iagreen的答案,而不是我的,然后我会在这里删除我的答案:) – BNK

0
TypeToken objtype= new TypeToken<Response>() {}.getType(); 
Response responseobj= new Gson().fromJson(responsestring, objtype); 

use Typetoken to parse Gson Object back to original one 
+0

我的地图仍然是空的,我怀疑问题是与Response类做 – noobcoder

1

Response代表并包含在一个名为map领域HashMap对象,但你的JSON代表只是一个Map。你并不需要有一个封闭的对象,只是反序列化HashMap直接 -

HashMap<String, ArrayList<ArrayList<String>>> map; 
Type mapType = new TypeToken<HashMap<String, ArrayList<ArrayList<String>>>>() {}.getType(); 
map = gson.fromJson(response, mapType); 
相关问题