8

Looking to parse some Json and parse out array of arrays. Unfortunately I cannot figure out how to handle nested arrays within the json.

json

{
    "type": "MultiPolygon",
    "coordinates": [
        [
            [
                [
                    -71.25,
                    42.33
                ],
                [
                    -71.25,
                    42.33
                ]
            ]
        ],
        [
            [
                [
                    -71.23,
                    42.33
                ],
                [
                    -71.23,
                    42.33
                ]
            ]
        ]
    ]
}

What I have implemented when I just an a single array.

public class JsonObjectBreakDown {
    public String type; 
    public List<List<String[]>> coordinates = new ArrayList<>();
    public void setCoordinates(List<List<String[]>> coordinates) {
        this.coordinates = coordinates;
    }




}

parsing call

JsonObjectBreakDown p = gson.fromJson(withDup, JsonObjectBreakDown.class);
user2524908
  • 861
  • 4
  • 18
  • 46
  • You basically have to iterate over each array, and get the nested array. Think of each array as its own object. So you get the object, then get the array object from that, and so on... – BlackHatSamurai Sep 19 '13 at 22:49

1 Answers1

11

You've got an array of arrays of arrays of arrays of Strings. You need

public List<List<List<String[]>>> coordinates = new ArrayList<>();

The following

public static void main(String args[]) {
    Gson gson = new Gson();
    String jsonstr ="{  \"type\": \"MultiPolygon\",\"coordinates\": [        [            [                [                    -71.25,                    42.33                ],                [                    -71.25,                    42.33                ]            ]        ],        [            [                [                    -71.23,                    42.33                ],                [                    -71.23,                    42.33                ]            ]        ]    ]}";
    JsonObjectBreakDown obj = gson.fromJson(jsonstr, JsonObjectBreakDown.class);

    System.out.println(Arrays.toString(obj.coordinates.get(0).get(0).get(0)));
}

public static class JsonObjectBreakDown {
    public String type; 
    public List<List<List<String[]>>> coordinates = new ArrayList<>();
    public void setCoordinates(List<List<List<String[]>>> coordinates) {
        this.coordinates = coordinates;
    }
}

prints

[-71.25, 42.33]
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724