我無法手動決議此 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 回應在這里
val food = JSONObject(bodys).getJSONObject("foods")
這導致了錯誤
java.lang.Error: org.json.JSONException: 值 [{"food_name":"skittles","brand_name":null,"serving_qty":1,"serving_unit":"se ... at foods of type org. json.JSONArray 無法轉換為 JSONObject
uj5u.com熱心網友回復:
那么你試圖直接從陣列中取出值而不回圈這是不可能的......
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")
}
我希望這能幫到您!!以后謝謝我!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/534393.html
