K.Os
K.Os

Reputation: 5496

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?

Upvotes: 18

Views: 37238

Answers (2)

Charlie Niekirk
Charlie Niekirk

Reputation: 1143

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.

Upvotes: 36

Purushotham
Purushotham

Reputation: 3820

Try this, it uses object instead of Type..

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

Upvotes: 7

Related Questions