android студийная организация. json. JSON .typeMismatch - PullRequest
0 голосов
/ 10 февраля 2020

Как я могу получить JSONObject с массивом в нем залпом?

Logi c

one

Код

Примечание: я знаю, что моя функция 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"
}

1 Ответ

1 голос
/ 10 февраля 2020

Вы можете проанализировать ваши json данные следующим образом

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_posts)

    callAPIDemo()
}

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 list: ArrayList<Post> = ArrayList()
                getPosts(response,list)

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


fun getPosts(response: String,list:ArrayList<Post>) {

        var jsonObject = JSONObject(response)
        val jsonArray = jsonObject.getJSONArray("posts")

        for (i in 0 until jsonArray.length()) {
            val jsonObject1 = jsonArray.getJSONObject(i)
            var listingObject = Post(
                    jsonObject1.getInt("id"),
                    jsonObject1.getString("user"),
                    jsonObject1.getString("slug"),
                    jsonObject1.getString("image"),
                    jsonObject1.getString("body"),
                    jsonObject1.getString("icon"),
                    jsonObject1.getString("quote"),
                    jsonObject1.getString("video"),
                    jsonObject1.getString("created_at"),
                    jsonObject1.getString("updated_at")

            )
            list.add(listingObject)

        }
}

И ваш класс данных будет выглядеть следующим образом

data class Post ( val id: Int, val user: String?, val slug: String?,
                      val image: String?, val body: String?, val icon: String?,
                      val quote: String?, val video: String?, val created_at: String?,
                      val updated_at: String?
    )
...