https://kotlinlang.org logo
#getting-started
Title
# getting-started
c

César

03/30/2022, 12:46 PM
hi! how do I achieve this?
Copy code
val courses: Collection<Course> = gson.fromJson(response.string(), Collection<Course>::class.java)
(the
Collection<Course>::class.java
part)
I was able to do it with
Copy code
val listOfMyClassObject: Type = object : TypeToken<Collection<Course>>() {}.type
        val courses: Collection<Course> = gson.fromJson(response.string(), listOfMyClassObject)
but
TypeToken
is a class from Gson so I'm still curious how it can be done without that
p

Paul Griffith

03/30/2022, 2:35 PM
Copy code
inline fun <reified T> Gson.fromJson(json: String): T {
    return fromJson(json, T::class.java)
}
would be, in use,
gson.fromJson<Collection<Course>>(response.string())
also, obligatory: don’t use GSON 🙂
c

César

03/30/2022, 2:38 PM
what do you recommend instead?
p

Paul Griffith

03/30/2022, 3:07 PM
The general recommendations are Moshi or Kotlin serialization I think GSON isn’t aware of Kotlin’s nullability, so you can deserialize something into an invalid state I’ve been able to use
kotlinx-serialization
but because it’s compile-time generation of code (to be multiplatform) it makes some tradeoffs that can make it more awkward to use for certain things
c

César

03/30/2022, 3:30 PM
thanks for the inputs. I remember using Moshi, I'll take a look at that tomorrow
k

Klitos Kyriacou

03/31/2022, 9:12 AM
You might also check if you're already pulling in a JSON library; for example, if you're using Spring, you might already have jackson-databind in your classpath, and Jackson has a Kotlin module too.
👍 1
3 Views