简体   繁体   中英

Read JSON double dimensional array in Java

I'm trying to get a string from a JSONObject.

My JSON looks like this :

{
    "agent":
    [
        {"name":"stringName1", "value":"stringValue1"},
        {"name":"stringName2", "value":"stringValue2"}
    ]
}

I want to get the values from stringName1 and stringName2. So first, I tried to get the "agent" using this :

JSONObject agent = (JSONObject) jsonObject.get("agent");

However, this throws me an error.

Have you got any idea on how to process ?

You're trying to parse a JSON array into a JSON object. Of course it's going to give you errors.

Try this instead:

JSONArray agent = jsonObject.getJsonArray("agent");

// To get the actual values, you can do this:
for(int i = 0; i < agent.size(); i++) {
    JSONObject object = agent.get(i);
    String value1 = object.get("name");
    String value2 = object.get("value");
}
 String Json=" { agent: [ {name:stringName1, value:stringValue1},{name:stringName2, value:stringValue2}]}";

You are parsing Jsonarray in to JsonObject that is why you are getting error.

JSONObject obj = new JSONObject(Json);
JSONArray array = obj.getJSONArray("agent");

 for(int i = 0 ; i < array.length() ; i++)
       {
   String strngNameOne=array.getJSONObject(i).getString("name");
   String stringNameTwo=array.getJSONObject(i).getString("value");
   //System.out.println(array.getJSONObject(i));
        }

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