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);
A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.
//Parsing the contents of the JSON file JSONObject jsonObject = (JSONObject) jsonParser. parse(new FileReader("E:/players_data. json")); Retrieve the value associated with a key using the get() method.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With