繁体   English   中英

如何从 retrofit 响应中获取嵌套的 JSON object 和数组?

[英]How to get nested JSON object and array from retrofit response on Android?

我想要做的是使用 ZBD279364F96CA5CBCAB793 得到嵌套的 JSON object 和数组形成 web 响应

回应是:

{
"user": [
    {          
      "name": "Kaleigh Stamm",          
      "post": {
        "id": 1234,            
        "link": [
          "https://www.link1.com"
          "https://www.link2.com"
          "https://www.link3.com"
        ]
      }
    }
}

我可以毫无问题地获得名称,但我无法解析 object 帖子,也无法解析可能是 null 或具有多个链接的链接数组。 我现在需要执行一些帖子 class 但不知道该怎么做

我有一个用户 class

class user {
    
    @SerializedName("name")
    var name = ""
    
}

我有一个界面

interface userService {
    @GET("baseurlinfo")
    fun getUserList() : Call<userResponse>
}

这是我的主要

var BaseUrl = "https://baseURL.com/"
    val retrofit = Retrofit.Builder()
            .baseUrl(BaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

    val service = retrofit.create(userService::class.java)

    val call = service.getUserList()
    call.enqueue(object : Callback<userResponse> {
        override fun onResponse(call: Call<userResponse>, response: Response<userResponse>) {
            if (response.code() == 200) {
                val userResponse = response.body()!!
                for( user in userResponse.user){
                    Log.v("MainActivity", user.name)
                }
            }
        }
        override fun onFailure(call: Call<userResponse>, t: Throwable) {
            Log.v("MainActivity", t.toString())
        }
    })

任何有关如何处理 JSON 响应的 rest 的帮助或建议都会非常好,谢谢。

您的用户 class 不完整。 首先在本站的 JSON 下方添加( json 到 pojo )。 然后得到 java class 然后粘贴到 android studio。 然后android studio自动转换为kotlin class。 然后只需从创建的用户 class 获取您的链接。 此外,您的 JSON 格式不正确,应如下所示:

{
"user": [
{          
  "name": "Kaleigh Stamm",          
  "post": {
    "id": 1234,            
    "link": [
      "https://www.link1.com",
      "https://www.link2.com",
      "https://www.link3.com"
    ]
  }
}
]
}

创建一个帖子 class 并从用户 class 调用它

class userPost {
    @SerializedName("id")
    private var mId: Int? = null

@SerializedName("link")
private var mLink: ArrayList<String>? = null

fun getId(): Int {
    return mId!!
}

fun setId(id: Int) {
    mId = id
}

fun getLink(): ArrayList<String> {
    return mLink!!
}

fun setLink(link: ArrayList<String>) {
    mLink= link
}

}

并在用户 class 添加

@SerializedName("post")
    private var mPost: userPost? = null

    fun getPost(): userPost? {
        return mPost
    }

    fun setPost(post: userPost) {
        mPost = post
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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