Gson tips

Object array to JsonArray

Object[] objects = {123, true, "abc"};
JsonArray jsonArray = new Gson().toJsonTree(objects).getAsJsonArray();

Add additional field when serialization

It could be used when you can not change the original class

class Box {
    int length;
    int width;

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }
}
public class JsonArrayTest {
    public static void main(String[] args) {
        Box box = new Box();
        box.setLength(10);
        box.setWidth(3);

        JsonElement jsonElement = new Gson().toJsonTree(box);
        jsonElement.getAsJsonObject().addProperty("area", 30);
        System.out.println(new Gson().toJson(jsonElement));
    }
}

Tags:

Categories:

Updated: