Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert GsonBuilder into Kotlin

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

like image 663
ZeroOne Avatar asked May 18 '17 14:05

ZeroOne


People also ask

How do I parse JSON array in Kotlin?

You can use JSON to Kotlin Data class converter plugin in Android Studio for JSON mapping to POJO classes (kotlin data class). This plugin will annotate your Kotlin data class according to JSON. Then you can use GSON converter to convert JSON to Kotlin. If you want to parse json manually.

What is @SerializedName in Kotlin?

The @SerializedName annotation can be used to serialize a field with a different name instead of an actual field name. We can provide the expected serialized name as an annotation attribute, Gson can make sure to read or write a field with the provided name.


1 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.

like image 194
hotkey Avatar answered Oct 22 '22 06:10

hotkey