Reputation: 401
I'm using Google Gson to serialize Java objects into JSON. For now, I'm using the registerTypeAdapter
method to add custom serialization for some classes.
By using this, I need to import into my project all the classes that I want to serialize.
Since I'm working on a project where an object can have custom classes attached, I'm looking for a solution where I create a particular method (for instance, toJson
) and tell Gson to search for that method before serializing in its default mode.
public class Banana {
...
public JsonObject toJson() {
// do stuff here
}
}
When Gson finds out that this method exists, it use it, otherwise it goes on using the default serialization.
Is this the correct way to do that? Is there an alternative method to include the serialization code into the class?
Upvotes: 0
Views: 630
Reputation: 12285
I believe you should use TypeAdapterFactory
.
Let your classes having custom serialization implement some interface, like:
interface CustomSerializable {
JsonObject toJson();
}
Then implement something like:
public class CustomTypeAdapterFactory implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
// if given type implements CustomSerializable return your TypeAdapter
// that is designed to use above mentioned interface
// so it uses method toJson() appropriately
// else return null for default serialization
return null;
}
}
Then it is just registering custom factory once, for example:
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new CustomTypeAdapterFactory())
.create();
If you cannot change classes to implement CustomSerializable
you can always also use reflection to determine inf there is a method toJson()
but that might have nasty side effects if there is such and not added by you.
Upvotes: 1