1

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 ?

1
  • "agent" is JSONArray. jsonObject.optJSONArray("agent"); Commented Jun 23, 2015 at 14:03

2 Answers 2

3

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");
}
Sign up to request clarification or add additional context in comments.

2 Comments

And to get the elements in the Array, use the get(int) method. Like: agent.get(0);.
Thanks for your help ! I had to change some code but it works ! I changed agent.size() to agent.length() and object.get("name") to object.getString("name").
0
 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));
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.