无法解析Kotlin中的JSONObject

ftf50wuq  于 2022-11-16  发布在  Kotlin
关注(0)|答案(1)|浏览(196)

我无法手动解析此JSONObject。

val client = OkHttpClient()
val mediaType = "application/x-www-form-urlencoded".toMediaTypeOrNull()
val body = RequestBody.create(mediaType, "query=${listItemName}")

val request = Request.Builder()
    .url("https://trackapi.nutritionix.com/v2/natural/nutrients")
    .method("POST", body)
    .build()

    val response = client.newCall(request).enqueue(object: Callback {
        override fun onFailure(call: Call, e: IOException) {
            println("Failed to execute request")
        }

        override fun onResponse(call: Call, response: Response) {
            val bodys = response.body?.string()
            println(bodys)

            val food = JSONObject(bodys)
            val foodName = food.getString("food_name")
          
        }


    })

system.out显示了JSONObject字符串,并且有一个“food_name”,但是我一直收到下面的错误

2022-11-15 13:21:52.096 30501-30580/com.cpg12.findingfresh I/System.out: {"foods":[{"food_name":"crab","brand_name":null,"serving_qty":1,"serving_unit":"cup, flaked and pieces","serving_weight_grams":118,"nf_calories":97.94,"nf_total_fat":0.87,"nf_saturated_fat":0.24,"nf_cholesterol":114.46,"nf_sodium":466.1,"nf_total_carbohydrate":0,"nf_dietary_fiber":0,"nf_sugars":0,"nf_protein":21.1,"nf_potassium":305.62

2022-11-15 13:21:52.103 30501-30580/com.cpg12.findingfresh E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
    Process: com.cpg12.findingfresh, PID: 30501
    java.lang.Error: org.json.JSONException: No value for food_name
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1139)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:761)
     Caused by: org.json.JSONException: No value for food_name

JSON响应为herex 1c 0d1x

val food = JSONObject(bodys).getJSONObject("foods")

这导致了错误
java.lang.Error:org.json.JSONException:值[{“食品名称”:“肉丝”,“品牌名称”:null,“供应数量”:1,“供应单位”:“se...在类型为org.json.的食品中。JSON数组无法转换为JSON对象

qacovj5a

qacovj5a1#

你试图直接从数组中取出值而不循环,这是不可能的...

val food = JSONObject(bodys) //here you are doing blunder

这应当

val food =JsonArray(bodys)

您所需要求的完整代码段

val response = JSONObject(bodys)
 val Jarray: JSONArray = response.getJSONArray("foods")
 for (i in 0 until Jarray.length()) {
        val jsonobject: JSONObject = jsonarray.getJSONObject(i)
        val food_name= jsonobject.getString("food_name")
       
    }

希望这对你有帮助!!以后谢谢我!!

相关问题