Giorgi
07/20/2023, 6:50 PM((Json.decodeFromString<JsonObject>(response.bodyAsText())["onResponseReceivedActions"] as JsonArray)[0] as JsonObject)["reloadContinuationItemsCommand"]
If I use JSON to kotlin class plugin then I get 110 different objects and for some reason the code does not compileeygraber
07/20/2023, 6:52 PMGiorgi
07/20/2023, 6:58 PMGiorgi
07/20/2023, 6:58 PMkevin.cianfarini
07/20/2023, 6:59 PMval json = Json {
ignorUnknownKeys = true
}
and then write your model as
@Serializable class Response(
val onResponseReceivedAction: List<SomeType>
)
You should be able to do thisCasey Brooks
07/20/2023, 7:01 PMmbonnin
07/20/2023, 7:14 PMfun JsonElement.toAny(): Any? {...}
inline fun <reified T> Any?.cast() = this as T
val Any?.asMap: Map<String, Any?>
get() = this.cast()
val Any?.asList: List<Any?>
get() = this.cast()
val Any?.asString: String
get() = this.cast()
val Any?.asBoolean: String
get() = this.cast()
val Any?.asNumber: Number
get() = this.cast()
Then you can write
Json.decodeFromString(response.text())
?.asMap["onResponseReceivedActions"]
?.asList[0]
?.asMap["reloadContinuationItemsCommand"]
It's not perfect but you don't have to go back all the time to open those cast parenthesis yell at parenthesisephemient
07/20/2023, 11:42 PMJson.decodeFromString<JsonElement>(response.bodyAsText())
.jsonObject["onResponseReceivedActions"]!!
.jsonArray[0]
.jsonObject["reloadContinuationItemsCommand"]!!
.jsonPrimitive.contentmbonnin
07/21/2023, 8:29 AMJsonElement. I guess the .jsonObject vs .asObject got me a bit confused initially and I never questioned this again. Also I'd really like to see this cast<T>() method reach stdlib one day so I'm practicing it 😄Mohammed Akram Hussain
07/21/2023, 11:07 AMmbonnin
08/16/2023, 4:24 PMwhy? if you just use the extensions already in kotlinx.serialization.jsonJust bumped into one of the reason.
.jsonPrimitive.content will return "null" instead of null if the string is nullable so it needs extra carembonnin
08/16/2023, 4:25 PM.jsonObject . If you object is nullable, it'll throw so you'll have to manage that manually at which point might as well write your own extensions