Kotlin convert json string to ojbect list using gson

I have a problem with Kotlin writing code to convert from json String to a list of objects.

Normal in Java is something 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 

Android Studio IDE underlines as TypeToken error:

Unable to access <init> ': this is public / package / in' TypeToken '

and also underlines as an error {}:

Type mismatch. Necessary: ​​Type! Found: () → Unit

So, is there a solution to make it work for Kotlin?

+2
source share
2 answers

Instead, you can try:

val objectList = gson.fromJson(json, Array<SomeObject>::class.java).asList()

This should do the job.

+3

, .

measurements : List<SomeOjbect> = gson.fromJson(text, object : TypeToken<List<SomeOjbect>>() {}.type) 
+1

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


All Articles