Gson - avoid unnecessary wrapper classes when serializing

I have a Json string:



I want to serialize this into an array of classes Location

using Gson


public class Location {
    public double elevation;
    public double latitude;
    public double longitude;
    public String name;


Instead of creating a class Locations

and a wrapper class with a field Locations

. Is it possible how?


source to share

2 answers

This should work:

jsonStr = "...";

Class<? extends HashMap> mapType = new HashMap<String, Object>().getClass();
Map data = new Gson().fromJson(job.jobContext, mapType);

JsonObject locations = data.get("Locations").getAsJsonObject();
JsonArray locationAry = locations.get("Location").getAsJsonArray();

for(JsonElement jsonEle: locationAry) {
   Location loc = new Location();
   JsonObject jsLoc = jsonEle.getAsJsonObject();
   loc.elevation = jsLoc.get("elevation").getAsInt();
   // ...




You can get an object Locaitons

and then an array Location

. 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<List<Location>>(){}.getType();

JsonArray locationJsonList = (JsonArray) ((JsonObject) gson.fromJson(jsonAsText, JsonObject.class).get("Locations")).get("Location");
List<Location> locatioList = gson.fromJson(locationJsonList, listType);




All Articles