Skip to content

Custom Serializers fail if the serializer context is used on the source #43

Closed

Description

Gson will fail to serialize a class "Foo" if you create a custom serializer
as follows:

public static class FooTypeAdapter implements JsonSerializer<Foo> {
  public JsonElement serialize(Foo src, Type typeOfSrc,
JsonSerializationContext context) {
    return context.serialize(src, typeOfSrc);
  }
}

Basically, it detects this as a circular reference.  Instead, we should
allow this kind of custom serializer because a client may want to perform
the default serialization of an object and then add new fields into the
JsonElement tree.

For example:
public static class FooTypeAdapter implements JsonSerializer<Foo> {
  public JsonElement serialize(Foo src, Type typeOfSrc,
JsonSerializationContext context) {
    JsonElement element = context.serialize(src, typeOfSrc);
    JsonObject jsonObject = element.getAsJsonObject();
    jsonObject.add("someNewProperty", new JsonPrimitive(1L));
    return jsonObject;
  }
}

Original issue reported on code.google.com by joel.leitch@gmail.com on 14 Sep 2008 at 7:53

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions