我已经尝试http://www.jsonschema2pojo.org/来解决这个问题,但它还没有奏效。我正在尝试为这个Json格式创建一个Json响应类:
{
"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 :(得分:1)
您的Response
代表的对象和名为HashMap
的字段中包含map
的对象,但您的JSON仅代表Map
。您不需要拥有封闭对象,只需直接反序列化HashMap
-
HashMap<String, ArrayList<ArrayList<String>>> map;
Type mapType = new TypeToken<HashMap<String, ArrayList<ArrayList<String>>>>() {}.getType();
map = gson.fromJson(response, mapType);
答案 1 :(得分: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);
按以下方式调试屏幕截图:
希望这有帮助!
答案 2 :(得分:0)
TypeToken objtype= new TypeToken<Response>() {}.getType();
Response responseobj= new Gson().fromJson(responsestring, objtype);
use Typetoken to parse Gson Object back to original one