Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a serializer for Gson using Java 8

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?

like image 401
principal-ideal-domain Avatar asked Oct 17 '25 01:10

principal-ideal-domain


1 Answers

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.

like image 154
Boris the Spider Avatar answered Oct 19 '25 16:10

Boris the Spider