Home » Android » java – Convert GsonBuilder into Kotlin

java – Convert GsonBuilder into Kotlin

Posted by: admin June 15, 2020 Leave a comment

Questions:

Does anyone know how to convert this code into kotlin

GsonBuilder builder = new GsonBuilder();
builder.setLenient();
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            if (json.getAsJsonPrimitive().isNumber()) {
                return new Date(json.getAsJsonPrimitive().getAsLong() * 1000);
            } else {
                return null;
            }
        }
    });
return builder.create();

Then, i tried

val builder = GsonBuilder()
builder.setLenient()
builder.registerTypeAdapter(Date::class.java,.........)
return builder.create()

….. i can’t figured it out how to convert the code

How to&Answers:

The code line that you are asking about can be converted to the following Kotlin code:

builder.registerTypeAdapter(Date::class.java, JsonDeserializer<Date> { 
    json, typeOfT, context ->
    if (json.getAsJsonPrimitive().isNumber())
        Date(json.asJsonPrimitive.asLong * 1000) else
        null
})

First, Kotlin supports SAM conversion of lambdas to Java interfaces, but the syntax is different to Java. Then, returns inside lambdas have different meaning to that in Java, and should be replaced with implicit returns or labeled returns.

Answer:

Thanks, i already figured it out.. is it the correct way to do it, any expert can comment

    @Provides
    @Singleton
    fun provideGson(): Gson? {
        val builder = GsonBuilder()
        builder.setLenient()
        builder.registerTypeAdapter(Date::class.java, JsonDeserializer<Date> { json, typeOfT, context ->
            if (json.asJsonPrimitive.isNumber) {
                Date(json.asJsonPrimitive.asLong * 1000)
            } else {
                null
            }
        })
        return builder.create()
    }

Answer:

val gson = GsonBuilder().apply {
        setLenient()
        registerTypeAdapter(Date::class.java,
                JsonDeserializer<Date> { json, typeOfT, context ->
                    if(json.asJsonPrimitive.isNumber) {
                        Date(json.asJsonPrimitive.asLong * 1000)
                    } else {
                        null
                    }
                })
    }.create()