Home > Blockchain >  Unable to parse JSONObject in kotlin
Unable to parse JSONObject in kotlin

Time:11-16

I am unable to parse this JSONObject manually.

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



    })

The system.out shows the JSONObject string and there is a "food_name" but I keep getting the error below

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

The JSON response is hereJSON response

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

This resulted in the error

java.lang.Error: org.json.JSONException: Value [{"food_name":"skittles","brand_name":null,"serving_qty":1,"serving_unit":"se ... at foods of type org.json.JSONArray cannot be converted to JSONObject

CodePudding user response:

Well you are trying to directly take out the value from array without loop it is not possible...

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

this should be

val food =JsonArray(bodys)

Full Code Snippet for your desire requirement

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

I hope this will help you!! Thanks me later!!

  • Related