I am considering switching over to Gson.
From my beginner's knowledge, I know of two ways to implement custom serializers and deserializers:
JsonSerializer
andJsonDeserializer
, andTypeAdaptor
.
Consider the following:
public class Pojo {
@JsonAdaptor(MyCustomAdaptor.class)
private Integer number;
}
class MyCustomAdaptor extends TypeAdaptor<Integer> {
@Override
public Integer read(JsonReader in) throws IOException {
// ...
}
public void write(JsonWriter writer, Integer value) throws IOException {
// ...
}
}
I noticed that TypeAdaptor
does not expose the Field
of number
. Nor is this the case with JsonSerializer
and JsonDeserializer
. I understand that by the time these classes are used in the marshaling/unmarshalling lifecycle, there is no need to know this information.
For a moment, let's pretend that the Field
was exposed in TypeAdaptor
s. The following is a basic example of what I would do:
public class Pojo {
@JsonAdaptor(MyCustomAdaptor.class)
@FloatSerialize
private Number number;
}
class MyCustomAdaptor extends TypeAdaptor<Number> {
@Override
public Number read(JsonReader in, Field field) throws IOException {
// Do something if @FloatSerialize is present.
}
public void write(JsonWriter writer, Number value, Field field) throws IOException {
// Do something if @FloatSerialize is present.
}
}
I know this would not make sense because @JsonAdaptor
can be used on classes and fields.
Also, I know there are better ways to accomplish the above example; it is just an example and is meaningless. Basically, I want to use annotations, on a per-field basis, to tell custom serializers/deserializers how to process.
Is this possible with Gson? Can you create a custom serializer/deserializer that exposes the annotated class/field/etc?