hi! how do I achieve this? ```val courses: Collect...
# getting-started
c
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
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
what do you recommend instead?
p
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
thanks for the inputs. I remember using Moshi, I'll take a look at that tomorrow
k
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