简体   繁体   中英

How create nested JSON by Kotlinx Serialization on Kotlin native

I creating a Shared lib by Kotlin multiplatform and I use Kotlin Serialization library for Serialize and Deserialize, I Implementing Graph QL on my project and I use below struct

{
 "operationName":"Operation",
 "query":"query Operation($id: ID){rres: Cards(id: $id){id}}",
 "variables":{"id": 1}
}

for communication with API , now I have a issue that I should fill a Json as a Object in variables by Kotlinx.Serialization but I don't find a way for it while I fill varibales as String and API get exception to me.

How I create a nested Json by Kotlinx.Serialization?

You need to make a class for nested Json objects and annotate it with @Serializable

@Serializable
class Data(
    val operationName: String,
    val query: String,
    val variables: Variables
) {
    @Serializable
    class Variables(val id: Int)
}

You might want to have a look at here. I think this thread exactly tackles the issue of storing the object as a Json string, that is nested in another Json.

https://github.com/Kotlin/kotlinx.serialization/issues/345#issuecomment-457545923

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM