简体   繁体   中英

Moshi and Retrofit2: Unable to read service response

I'm trying to read a json response from a webservice, but without success. This is the json i receive:

{
  "rsp": {
          "@code": "0",
          "@message": ""
       },
  "listOfStrings":[]
}

And this is relative data class where i parse response

data class Response(
    val rsp : Rsp,
    val listOfStrings : List<String>
)

data class Rsp(
    @Json(name = "@code")
    val code : String,
    @Json(name = "@message")
    val message : String
)

But it seems that moshi for some reason it's not able to parse json into object, because i always get Response object with all null fields.

So what's wrong? May the "@" character of json response fields cause problems?

UPDATE

Now i can parse correctly response by change @Json annotation into @field:Json:

data class Rsp(
    @field:Json(name = "@code")
    val code : String,
    @field:Json(name = "@message")
    val message : String
)

But i'm curious to know why it works.

@field:如果您希望 moshi-kotlin 根据此处的讨论与 proguard 一起使用,则需要 Json: https : //github.com/square/moshi/issues/315

Try this model and let me know if it works:

@Parcelize
data class Response(
    @Json(name = "rsp")
    val rsp: Rsp,
    @Json(name = "listOfStrings")
    val listOfStrings: List<String>
) : Parcelable {
    @Parcelize
    data class Rsp(
        @Json(name = "@code")
        val code: String,
        @Json(name = "@message")
        val message: String
    ) : Parcelable
}

Edit: If it didn't work, try to add back-slash behind those field names that have @ .

Like: @Json(name = "\\@code") .

UPDATE AFTER QUESTION GOT UPDATE:
You need to add moshi-kotlin dependency and then using KotlinJsonAdapterFactory

val moshi = Moshi.Builder()
    // ... add your own JsonAdapters and factories ...
    .add(KotlinJsonAdapterFactory())
    .build()

Then moshi couldn't ignore @Json .

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