Reputation: 1845
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 ?
Upvotes: 1
Views: 102
Reputation: 2208
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));
}
Upvotes: 0
Reputation: 4292
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");
}
Upvotes: 3