简体   繁体   中英

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM