Jonathan Aurry Jonathan Aurry - 27 days ago 10
Java Question

How to parse multidimensional array in JSON for android

so I read some asked questions about this but I think people misunderstood what is multidimensional array.

In my case I want to parse a "real" 2d array, I need to parse a JSON with coordinates to place markers and draw lines. I easily parse markers but for lines I have this type of data:

"coordinates": [
[
2.33849,
48.8896,
0
],
[
2.33847,
48.88955,
0
],
[
2.33846,
48.88951,
0
],
.....


If I just do "JSONArray lines = geometry.getJSONArray("coordinates");" I will not have what I need wich is the arrays of coordinates.

How can I do to have each array with the two coordinates?

Any tips, comment ,code sample will be appreciated! Thanks

Answer
        JSONArray lines = geometry.getJSONArray("coordinates");
        double[][] coords = new double[lines.length()][];
        for (int i = 0; i < lines.length(); i++) {
            JSONArray xyJson = lines.getJSONArray(i);
            coords[i] = new double[xyJson.length()];   // length is always 2
            for (int j = 0; j < xyJson.length(); j++) {
                coords[i][j] = xyJson.getDouble(j);
            }
        }
Comments