18

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?

3
  • 1
    Try this, it uses object instead of Type.. measurements : List<SomeOjbect> = gson.fromJson(text, object : TypeToken<List<SomeOjbect>>() {}.type) Commented Dec 15, 2017 at 6:19
  • @Uttam Thanks, it worked. You can post it as an answer and i accept it Commented Dec 15, 2017 at 13:14
  • Glad that it helps you.. Commented Dec 18, 2017 at 16:14

2 Answers 2

36

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow! Thats the biggest change in my android networking stack :D
7

Try this, it uses object instead of Type..

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.