Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

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

What I am trying to do is get the nested JSON object and array form the web response using retrofit

the response is:

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

I can get the name with no problem, but I have not been able to parse the post object neither the link array which could be null or have several links. I now that some post class needs to be implemented but do not know quite how to do it

I have a user class

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

I have an interface

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

And this is my main

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())
        }
    })

Any help or suggestion on how to process the rest of the JSON response would be great, thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

create a post class and call it from the user 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
}

}

And on the user class add

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

    fun getPost(): userPost? {
        return mPost
    }

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...