Make Flat JSON Using Gson ()

I would like to create a "flat" class JSON.

Suppose I have a class:

public class Parcel {
private double area;
private int type;
private Address address;
}

and

public class Address {
private String street;
private int number;
private int flatNumber;
}

Is there any chance to make JSON as follows:

{
"area":0.0,
"type":1,
"Address.street":"street name",
"Address.number":22,
"Address.flatNumber":29
}

I do not need to deserialize JSON. I need to send it to WS.

+4
source share
1 answer

One option is to write a custom serializer so that you can control the json schema you want to send.

private static class ParcelSerializer implements JsonSerializer<Parcel> {
    @Override
    public JsonElement serialize(Parcel src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject obj = new JsonObject();
        obj.addProperty("area", src.area);
        obj.addProperty("type", src.type);
        JsonObject addrObj = context.serialize(src.address, Address.class).getAsJsonObject();
        for(Map.Entry<String, JsonElement> e : addrObj.entrySet()) {
            obj.add("Address."+e.getKey(), e.getValue());
        }
        return obj;
    }
}

Then you just need to register it in GsonBuilder:

Gson gson = new GsonBuilder().setPrettyPrinting().registerTypeAdapter(Parcel.class, new ParcelSerializer()).create();
String json = gson.toJson(p, Parcel.class);

Given your example, it outputs:

{
  "area": 0.0,
  "type": 1,
  "Address.street": "street name",
  "Address.number": 22,
  "Address.flatNumber": 29
}
+4
source

All Articles