Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin convert json string to list of object using Gson

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?

like image 684
K.Os Avatar asked Dec 14 '17 23:12

K.Os


1 Answers

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.

like image 51
Charlie Niekirk Avatar answered Sep 24 '22 00:09

Charlie Niekirk