I have a Json String:
{
"Locations":{
"Location":[{
"elevation":"100",
"latitude":"0",
"longitude":"0",
"name":"Ocean"
},
...
]}
}
I want to serialize this into an array of Location classes using Gson:
public class Location {
public double elevation;
public double latitude;
public double longitude;
public String name;
}
Rather than making a Locations class and a wrapper class with a Locations field. Is this possible + how?
You can get the Locaitons object and then the Location array. Below code is pure Gson:
String jsonAsText = "{\"Locations\":{\"Location\":[{\"elevation\":\"100\",\"latitude\":\"0\",\"longitude\":\"0\",\"name\":\"Ocean\"},{\"elevation\":\"100\",\"latitude\":\"0\",\"longitude\":\"0\",\"name\":\"Ocean\"}]}}";
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
java.lang.reflect.Type listType = new com.google.gson.reflect.TypeToken<List<Location>>(){}.getType();
JsonArray locationJsonList = (JsonArray) ((JsonObject) gson.fromJson(jsonAsText, JsonObject.class).get("Locations")).get("Location");
List<Location> locatioList = gson.fromJson(locationJsonList, listType);
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