Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Polymorphism with Gson

$
0
0

1. Introduction

In this tutorial, we’ll explore how to manage polymorphism with Gson. We’ll also explore some techniques for handling serialization and deserialization in polymorphic ways.

2. Polymorphism in JSON

Polymorphism in Java is well understood. We have a class hierarchy such that, when appropriate, we can treat different but related types the same in certain ways.

For example, we might have some definitions of various 2D shapes. Different shapes are defined in different ways, but they all have some common features — they can all calculate an area, for example.

As such, we could define some polymorphic classes for defining some shapes as:

interface Shape {
    double getArea();
}
class Circle implements Shape {
    private final double radius;
    private final double area;
    Circle(double radius) {
        this.radius = radius;
        this.area = Math.PI * radius * radius;
    }
    @Override
    public double getArea() {
        return area;
    }
}
class Square implements Shape {
    private final double side;
    private final double area;
    Square(double side) {
        this.side = side;
        this.area = side * side;
    }
    @Override
    public double getArea() {
        return area;
    }
}

Each of these shapes has its own concerns, but if we only care that each is a Shape and we can calculate its area, we can treat them all the same.

But how does this relate to JSON? We obviously can’t have functionality in a JSON document, but we can have data that overlaps, and we might want to have polymorphic classes represented in a reasonable way in our JSON.

For example, the above shapes might be represented:

[
    {
        "shape": "circle",
        "radius": 4,
        "area": 50.26548245743669
    }, {
        "shape": "square",
        "side": 5,
        "area": 25
    }
]

If we want to treat these simply as Shape instances, we already have the area available to us. However, if we want to know exactly what shapes they are, then we can identify this and extract extra information from them.

3. Using a Wrapper Object

The easiest way to solve this is to use a wrapper object and different fields for each of our types:

class Wrapper {
    private final Circle circle;
    private final Square square;
    Wrapper(Circle circle) {
        this.circle = circle;
        this.square = null;
    }
    Wrapper(Square square) {
        this.square = square;
        this.circle = null;
    }
}

Using something like this, our JSON will then look like:

[
    {
        "circle": {
            "radius": 4,
            "area": 50.26548245743669
        }
    }, {
        "square": {
            "side": 5,
            "area": 25
        }
    }
]

This isn’t technically polymorphic, and it does mean that the JSON is a different shape from what we had seen earlier, but it’s very easy to implement. In particular, we only need to write our wrapper type, and Gson will automatically do everything for us:

List<Wrapper> shapes = Arrays.asList(
    new Wrapper(new Circle(4d)),
    new Wrapper(new Square(5d))
);
Gson gson = new Gson();
String json = gson.toJson(shapes);

Deserializing this also works exactly as we’d expect:

Gson gson = new Gson();
Type collectionType = new TypeToken<List<Wrapper>>(){}.getType();
List<Wrapper> shapes = gson.fromJson(json, collectionType);

Note that we need to use a TypeToken here because we’re deserializing to a generic list. This has nothing to do with our wrapper type and polymorphic structures.

However, this does mean that our Wrapper type needs to support every possible subtype. Adding new ones means a bit more work to achieve our desired end result.

4. Adding Type Field to Object

If we’re only interested in serializing our objects, we can simply add a field to them to indicate the type:

public class Square implements Shape {
    private final String type = "square"; // Added field
    private final double side;
    private final double area;
    public Square(double side) {
        this.side = side;
        this.area = side * side;
    }
}

Doing this will cause this new type field to appear in the serialized JSON, allowing clients to know which type each of the shapes is:

{
    "type": "square",
    "radius": 5,
    "area": 25
}

This is now closer to what we saw earlier. However, we can’t easily deserialize this JSON using this technique, so it’s only really viable in cases where we don’t need to do this.

5. Custom Type Adapter

The final way that we’re going to explore is by writing a custom type adapter. This is some code that we can contribute to the Gson instance that will then handle serializing and deserializing our types for us.

5.1. Custom Serializer

The first thing that we want to achieve is to be able to serialize our types correctly. This means serializing them with all of the standard logic but then adding an additional type field indicating the type of the object.

We achieve this by writing a custom implementation of JsonSerializer for our types:

public class ShapeTypeAdapter implements JsonSerializer<Shape> {
    @Override
    public JsonElement serialize(Shape shape, Type type, JsonSerializationContext context) {
        JsonElement elem = new Gson().toJsonTree(shape);
        elem.getAsJsonObject().addProperty("type", shape.getClass().getName());
        return elem;
    }
}

Note that we need to use a new Gson instance to serialize the value itself. If we reused the original instance – via the JsonSerializationContext – then we’d end up in an infinite loop where the serializer keeps calling itself.

Here, we’re using the full class name as our type, but we can equally use anything that we want to support this. We just need some way to uniquely convert between this string and the class name.

Using this, the resulting JSON will be:

[
    {
        "radius": 4,
        "area": 50.26548245743669,
        "type": "com.baeldung.gson.polymorphic.TypeAdapterUnitTest$Circle"
    },
    {
        "side": 5,
        "area": 25,
        "type": "com.baeldung.gson.polymorphic.TypeAdapterUnitTest$Square"
    }
]

5.2. Custom Deserializer

Now that we can serialize our types into JSON, we need to be able to deserialize them as well. This means understanding the type field and then using that to deserialize it into the correct class.

We achieve this by writing a custom implementation of JsonDeserializer for our types:

public class ShapeTypeAdapter implements JsonDeserializer<Shape> {
    @Override
    public Shape deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();
        String typeName = jsonObject.get("type").getAsString();
        try {
            Class<? extends Shape> cls = (Class<? extends Shape>) Class.forName(typeName);
            return new Gson().fromJson(json, cls);
        } catch (ClassNotFoundException e) {
            throw new JsonParseException(e);
        }
    }
}

We can implement both our serializer and deserializer within the same class by simply implementing both interfaces. This helps keep the logic together so that we know that the two are compatible with each other.

As before, we need to use a new Gson instance to actually do the deserializing. Otherwise, we’ll end up in an infinite loop.

5.3. Wiring in the Type Adapter

Now that we’ve got a type adapter that can be used to serialize and deserialize our polymorphic types, we need to be able to use it. This means creating a Gson instance that has it wired in:

GsonBuilder builder = new GsonBuilder();
builder.registerTypeHierarchyAdapter(Shape.class, new ShapeTypeAdapter());
Gson gson = builder.create();

We wire it in using the registerTypeHierarchyAdapter call since this means that it will be used for our Shape class and anything that implements it. This will then cause this Gson instance to use this adapter whenever it attempts to serialize anything implementing our Shape interface into JSON or whenever we attempt to deserialize JSON into anything that implements the Shape interface:

List<Shape> shapes = List.of(new Circle(4d), new Square(5d));
String json = gson.toJson(shapes);
Type collectionType = new TypeToken<List<Shape>>(){}.getType();
List<Shape> result = gson.fromJson(json, collectionType);
assertEquals(shapes, result);

6. Summary

Here, we’ve seen a few techniques for managing polymorphic types with Gson, both serializing them to JSON and deserializing them back from JSON.

Next time you’re working with JSON and polymorphic types, why not try some of them out?

As always, the full code for this article is available over on GitHub.

       

Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>