Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson - Avoid unneccessary wrapper classes when serializing

Tags:

java

gson

wrapper

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?

like image 726
Eduardo Avatar asked Jan 20 '26 11:01

Eduardo


1 Answers

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);
like image 64
Devrim Avatar answered Jan 22 '26 01:01

Devrim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!