简体   繁体   中英

Accessing deeply nested JSON array with Moshi/Retrofit2

All I need is the "photo" array. My JSON looks like this:

 {
  "photos": {
    "page": 1,
    "pages": "1000",
    "perpage": 1,
    "total": "1000",
    "photo": [
      {
        "id": "44049202615",
        "owner": "159796861@N07",
        "secret": "cb8f476a4d",
        "server": "1958",
        "farm": 2,
        "title": "Murugan",
        "ispublic": 1,
        "isfriend": 0,
        "isfamily": 0
      }
    ]
  },
  "stat": "ok"
}

I'm new to Moshi/Retrofit. I saw this but I don't quite understand yet how to make that work. I thought I could do something quick and dirty to get the values I need so I can continue to build out my app (I'll go back later for a proper implementation).

My quick and dirty idea was this:

data class GalleryItem(@Json(name = "title") val caption: String,
                       @Json(name = "id") val id: String,
                       @Json(name = "url_s") val url: String?)

data class Photo(@Json(name = "photo") val galleryItems: List<GalleryItem>)

data class Photos(@Json(name = "photos") val photo: Photo)

I thought I could just return a "Photos" from my api and grab the gallery items. There's no crashes but it's not parsing correctly. I get the "Photos" object but "Photo" is null.

Any thoughts on how to access the data I need?

Unfortunately, the @Json annotation gets ignored in Kotlin classes . The workaround (from the link I just gave) is to use @field:Json instead. Try something like this for your data classes:

data class ResponseData(
    val photos: Photos
)

data class Photos(
    @field:Json(name = "photo") val galleryItems: List<GalleryItem>
)

data class GalleryItem(
    val id: String,
    val title: String
)

try this one!

data class Response(
    @Json(name = "photos")
    val photos: Photos,    
    
    @Json(name = "stat")
    val stat: String
)
        
data class Photos(
    @Json(name = "page")
    val page: Int,
        
    @Json(name = "pages")
    val pages: String,
        
    @Json(name = "photo")
    val photosList: List<Photo>
)
        
data class Photo(
    val id: String,
    val owner: String
)

Now you can access the photolist using

response.photos.photosList

You can easily create pojo from json using this tool. Visit this site. http://www.jsonschema2pojo.org/

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