Home > Net >  Convert a JSON string to a JSON array
Convert a JSON string to a JSON array

Time:08-01

I have this json string:

{"instance_1":
    {"age":31,
     "dominant_emotion":"happy",
     "dominant_race":"latino hispanic",
     "emotion":
        {"angry":8.507632937702477e-22,
         "disgust":0.0,
         "fear":1.7665077830484905e-27,
         "happy":100.0,
         "neutral":2.3138133631306346e-07,
         "sad":3.718035974227784e-18,
         "surprise":7.542845514851848e-09},
         "gender":"Woman",
         "race":
            {"asian":9.939994663000107,
            "black":3.6370791494846344,
            "indian":13.22726309299469,
            "latino hispanic":29.343268275260925,
            "middle eastern":20.388375222682953,
            "white":23.46402108669281},
            "region":{"h":769,"w":769,"x":345,"y":211}},
            "seconds":1.0934789180755615,
            "trx_id":"28a2ff23-27be-4308-a2d3-592461f280a0"}
        }
    }
}

I want to convert this JSON string to a JSON Array, but I've having some trouble doing so. I attempted using JSONParser but it gave me an error:

        JSONParser parser = new JSONParser();
        JSONArray array = (JSONArray)parser.parse(getPOSTResponse(uri, f).body());
        System.out.println(((JSONObject)array.get(0)).get("dominant_emotion"));
Exception in thread "main" java.lang.ClassCastException: class org.json.simple.JSONObject cannot be cast to class org.json.simple.JSONArray (org.json.simple.JSONObject and org.json.simple.JSONArray are in unnamed module of loader 'app')
    at com.datacollection.Detection.main(Detection.java:35)

CodePudding user response:

parser.parse is returning a JSONObjectbut you are expecting aJSONArray`.

A JSON array looks like [ data, here ] while a JSON object looks like {the: data, is: here}.

You have a JSON object where the key instance_1 corresponds to another JSON object.

Instead of casting to JSONArray, you could do something like

JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject)parser.parse(getPOSTResponse(uri, f).body());
System.out.println(obj.get("instance_1").get("dominant_emotion"));

CodePudding user response:

I think what you want to do is create an array of the JSON objects, not turn the object into an array. This link may help.

https://www.delftstack.com/howto/javascript/javascript-json-array-of-objects/#:~:text= Using Array of JSON Objects in JavaScript,iterate the objects array the same... More

  • Related