Bogdan Lashkov Bogdan Lashkov - 4 months ago 46
JSON Question

How can I parse array of json objects using GSON into JAVA two-dimensional array?

I Have such kind of JSON string:

[{
"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"
}]


And I need it to be parsed into two-dimensional array that will look like this:
enter image description here
How can I make it, using GSON java library?
Now I have only written this piece of code, that returns a list:

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


But the code above works only with JSON object of array, not with string I have shown above.

Answer

Could you please try the following and see the results:

// 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