advocateofnone
advocateofnone

Reputation: 2541

Gson custom serialization not working for java.lang.Object

I am writing a custom Gson serializer

public class DogSerializer implements JsonSerializer<Object> {
@Override
public JsonElement serialize(Object src, Type typeOfSrc, 
JsonSerializationContext context) {

  JsonObject obj = new JsonObject();
  obj.addProperty("name", "sasha");
  return obj;
}

I am also registering the serialzer like

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Object.class, new DogSerializer());

Now if I do System.out.println(gsonBuilder.create().toJson([My-Test-Class])) the serializer is never called. I want the serializer to be called for all fields when I pass My-test-Class. Object.class doesn't seem to work. What should I do?

Upvotes: 0

Views: 374

Answers (1)

Lyubomyr Shaydariv
Lyubomyr Shaydariv

Reputation: 21115

What should I do?

Redesign your approach if possible and bind other types. You cannot override serialization strategies for java.lang.Object and com.google.gson.JsonElement (as of 2.8.1 and prior by design):

// built-in type adapters that cannot be overridden
factories.add(TypeAdapters.JSON_ELEMENT_FACTORY);
factories.add(ObjectTypeAdapter.FACTORY);

Upvotes: 1

Related Questions