我无法手动解析此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")
}
})
系统.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
val food = JSONObject(bodys).getJSONObject("foods")
这导致了错误
Java.lang.Error:org.json.JSONException:Value[{"Food_name":"skittle","brand_name":NULL,"Serving_qty":1,"Serving_Unit":"无法将org.json.JSONArray类型的食品转换为JSONObject