I have a problem with Kotlin to write code for conversion from JSON String to List of objects.
Normally in Java, it is like this:
Gson gson = new Gson();
Type type = new TypeToken<List<SomeOjbect>>() {}.getType();
List<SomeOjbect> measurements = gson.fromJson(json, type);
return measurements;
However in Kotlin, when i try it like this:
val gson = Gson()
val type: Type = TypeToken<List<SomeOjbect>>{}.type
val measurements : List<SomeOjbect> = gson.fromJson(text, type)
return measurements
The IDE Android Studio underlines as error the TypeToken saying:
Cannot access ' < init > ': it is public/package/ in 'TypeToken'
and also underlines as error the {} saying:
Type mismatch. Required: Type! Found: () → Unit
So is there a solution to make it work for Kotlin?
You could try doing this instead:
val objectList = gson.fromJson(json, Array<SomeObject>::class.java).asList()
EDIT [14th January 2020]: You should NOT be using GSON anymore. Jake Wharton, one of the projects maintainers, suggests using Moshi, Jackson or kotlinx.serialization.
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