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