简体   繁体   中英

Getting value from an array in a JSON Object in Java?

I'm fairly new to REST API calls in Java and I'm currently encountering problems with trying to get the "item" section from the JSON object (below). I guess it also confuses me that "response" is an object in an array too?/

The JSON file is below:

{
"version": "1.0",
"code": 200,
"request":{"text":["seafood" ], "lang": "en", "type": "stimulus"},
"response":[{
    "text": "seafood",
    "items":[
         {"item": "Shrimp", "weight": 100, "pos": "noun" }, 
         {"item": "Lobster",…
     ]
}]
}

I have currently managed to get the "response" part of the object using:

BufferedReader in = new BufferedReader( 
    new InputStreamReader(conection.getInputStream()));
StringBuffer json = new StringBuffer();
while ((readLine = in.readLine()) != null) {
    json.append(readLine);
} 
in.close();
JSONParser parser = new JSONParser();
try{
    JSONObject object= (JSONObject) parser.parse(json.toString());
    Object response = json.get("response");
...

Up to this point, I get stuck. I don't know what to do to 'response' to get to "items", and if I try to cast 'response' as a JSONObject, it will return as null?

What I want to try and do is to get each "item" in the "items" part and put it in a list.

Help would be very much appreciated!

I think it should works:

JSONParser parser = new JSONParser();
try{
    JSONObject object= (JSONObject) parser.parse(json.toString());
    JSONArray response = object.getJSONArray("response");
    JSONObject responseObject = response.getJSONObject(0);
    JSONArray expectedArray = responseObject.getJSONArray("items");
    for (int i = 0; i < expectedArray.length(); i++) {
        String item = expectedArray.getJSONObject(i).getString("item");
        String weight = expectedArray.getJSONObject(i).getInt("weight");
        ......
        //Here you can create your custom object and add to your array. For example
        list.add(new MyOwnObject(item, weight));
    }
....

Because response is array, not object

You should check the documentation for JSONObject . It describes all of the methods which are available. Note that there is no method named get() . Instead, you probably want to use getJSONArray()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM