I have a own class called MyDate
and want to write a serializer of it for Gson. This code works:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(MyDate.class, new JsonSerializer<MyDate>() {
@Override
public JsonElement serialize(MyDate date, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(date.toString());
}
});
However I want to use the power of Java 8 and therefore tried
builder.registerTypeAdapter(MyDate.class, (date, typeOfSrc, context) ->new JsonPrimitive(date.toString()));
But here eclipse tells me
The target type of this expression must be a functional interface
What's wrong about that Java 8 code?
In order to replace an anonymous class with a lambda, the parameter must be a Single Method Interface (SMI).
This is an interface
with a single abstract
method.
GsonBuilder.registerTypeAdaper
takes an Object
as the second argument.
You need to first assign your lambda then pass in the method:
final JsonSerializer<MyDate> serializer = (date, typeOfSrc, context) -> new JsonPrimitive(date.toString());
builder.registerTypeAdapter(MyDate.class, serializer);
This way you tell compiler which SMI you would like to implement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With