Как я могу получить JSONObject с массивом в нем залпом?
Logi c
![one](https://i.stack.imgur.com/zEheD.png)
Код
Примечание: я знаю, что моя функция API ниже работает, если мой результат JSON Array, но я не уверен, как изменить его, чтобы получить JSON Object (как мой результат is)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_posts)
callAPIDemo()
}
// api code
private fun callAPIDemo() {
val mySlugValue: String = intent.getStringExtra("my_slug")
// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(this)
val url = "https://example.com/api/categories/$mySlugValue"
// Request a string response from the provided URL.
val stringRequest = StringRequest(
Request.Method.GET, url,
Response.Listener<String> { response ->
val jsonArray = JSONArray(response)
val list: ArrayList<Post> = ArrayList()
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
list.add(parseData(jsonObject))
}
// here you will have the complete list of data in your "list" variable
posts_list.layoutManager = LinearLayoutManager(this)
Log.d("my list", list.toString())
posts_list.adapter = MyPostsRecyclerViewAdapter(list)
},
Response.ErrorListener { error ->
//displaying the error in toast if occurrs
Toast.makeText(applicationContext, error.message, Toast.LENGTH_SHORT)
.show()
})
// Add the request to the RequestQueue.
queue.add(stringRequest)
}
// parsing data
private fun parseData(jsonObject: JSONObject): Post {
var listingObject = Post(
jsonObject.getString("name"),
jsonObject.getString("slug"),
jsonObject.getString("image")
)
return listingObject
}
Есть идеи?
Обновление
В соответствии с просьбой, вот как выглядит мой возвращаемый код:
{
"id": 10,
"name": "...",
"slug": "...",
"icon": "...",
"body": "...",
"image": "...",
"posts": [
{
"id": 2,
"user": "...",
"name": "...",
"slug": "...",
"image": "...",
"body": "...",
"icon": null,
"quote": null,
"video": null,
"created_at": "2019-11-23 06:05:56",
"updated_at": "2019-11-23 06:53:26"
},
// other posts
],
"created_at": "2019-11-23 05:35:31",
"updated_at": "2019-11-26 11:25:17"
}