I want to get “file” in “media_gallery_entries” JSONArray by Volley for loop
Volley
val item = ArrayList<RecyData>()
val jsonRequest = object : JsonObjectRequest(Request.Method.GET, url, null,
Response.Listener { response ->
try {
val jsonArrayItems = response.getJSONArray("items")
val jsonSize = jsonArrayItems.length()
for (i in 0 until jsonSize) {
val jsonObjectItems = jsonArrayItems.getJSONObject(i)
val pName = jsonObjectItems.getString("name")
val pPrice = jsonObjectItems.getInt("price")
item.add(RecyData(pName, pPrice, pImage))
}
} catch (e: JSONException) {
e.printStackTrace()
}
Data
{
"items": [
{
"id": 1,
"sku": "10-1001",
"name": "item01",
"price": 100,
"media_gallery_entries": [
{
"id": 1,
"file": "//1/0/10-28117_1_1.jpg"
}
]
}
]
}
Try this code after val pPrice = jsonObjectItems.getInt("price")
this line
val mediaEntryArr = jsonObjectItems.getJSONArray("media_gallery_entries")
for(j in 0 until mediaEntryArr.length()){
val mediaEntryObj = mediaEntryArr.getJSONObject(j)
val id = mediaEntryObj.getString("id")
val file = mediaEntryObj.getString("file")
Log.e("mediaEntry----",""+ Gson().toJson(mediaEntryObj))
Log.e("id----",""+ id)
Log.e("file----",""+ file)
}
Instead of doing manual JSON
parsing which is always error prone, you can use some parsing library such as Gson which is well tested and very less likely to cause any issue
To use Gson
first you need to add dependency in your build.gradle as
implementation 'com.google.code.gson:gson:2.8.7'
Now define kotlin types which maps to your JSON response
class Media(
val id: Int,
val file: String
)
class Entry(
val id: Int,
val sku: String,
val name: String,
val price: Int,
val media_gallery_entries: List<Media>
)
Now in response listener just do
try{
val jsonArrayItems = response.getJSONArray("items")
val token = TypeToken.getParameterized(ArrayList::class.java, Entry::class.java).type
val result:List<Entry> = Gson().fromJson(jsonArrayItems.toString(), token)
// Do something with result
}
catch (e: JSONException) {
e.printStackTrace()
}