简体   繁体   中英

Moshi and retrofit2: parse content of root element

Since today i've received json responses like:

{
   "status" : "Ok",
   "otherField" : "Somevalues" 
}

That i map into classes like

data class MyResponse(
    val status : String,
    val otherField : String
)

Now response structure is changed in something like

{
   "rootElement" : {
       "status" : "Ok",
       "otherField" : "Somevalues" 
    }
}

There's a way to tell Moshi to parse directly content of "rootElement" whithout changing "MyResponse" structure?

There's a way to tell Moshi to parse directly content of "rootElement" whithout changing "MyResponse" structure?

If I understood your requirement properly, yes you can parse the content of rootElement without altering MyResponse data class. Create one more Kotlin data class like below

data class ResponseRoot (
    val rootElement : MyResponse
)

And use this ResponseRoot data class return type for your Retrofit Response instead of MyResponse class.

In your API interface just do the changes

@GET("url/here/")
fun fooBar(/* paramters if there any */): Call<ResponseRoot>

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