Convert GsonBuilder to Kotlin

Does anyone know how to convert this code to 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 not figure out how to convert the code

+6
source share
3 answers

The line of code you are asking for 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 converting SAM lambdas to Java interfaces , but the syntax is different from Java. Then the return inside lambdas has a value different from the value in Java, and it should be replaced with implicit returns or with the inscription return .

+8
source

, , ,

    @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()
    }
0
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()
0

Source: https://habr.com/ru/post/1017349/


All Articles