我有这样的JSON字符串:
[{
"id": 3,
"city": "Ilmenau",
"floor": null,
"housenumber": "35",
"streetname": "Blumenstraße",
"zip": "98693"
}, {
"id": 4,
"city": "Berlin",
"floor": null,
"housenumber": "54",
"streetname": "Bogdansplatz",
"zip": "194354"
}]
我需要将它解析为二维数组,如下所示: enter image description here 我怎样才能使用GSON java库? 现在我只写了这段代码,返回一个列表:
String s=getJson("SELECT * FROM address;");
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(s);
JsonArray jsonArr = jo.getAsJsonArray("array");
//jsonArr.
Gson googleJson = new Gson();
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
System.out.println("List size is : "+jsonObjList.size());
System.out.println("List Elements are : "+jsonObjList.toString());
但上面的代码只适用于数组的JSON对象,而不是我上面显示的字符串。
答案 0 :(得分:1)
请您尝试以下内容并查看结果:
// String 's' holds the JSON
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = (JsonArray) jsonParser.parse(s);
// this object is used to get the keys
JsonObject firstJsonObject = jsonArray.get(0).getAsJsonObject();
Set<java.util.Map.Entry<String, JsonElement>> entrySet = firstJsonObject.entrySet();
// declare two dimensional array
Object[][] array = new Object[entrySet.size()][jsonArray.size() + 1];
// the first column of the two-dimensional array is populated
Iterator<java.util.Map.Entry<String, JsonElement>> itr = entrySet.iterator();
for (int i = 0; itr.hasNext(); i++) {
array[i][0] = itr.next().getKey();
}
// the rest of the columns are populated
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject obj = (JsonObject) jsonArray.get(i);
for (int j = 0; j < array.length; j++) {
String key = array[j][0].toString();
JsonElement value = obj.get(key);
array[j][i + 1] = value instanceof JsonNull ? null : value.getAsString();
}
}
// now the two dimensional array is fully populated