2

Code is written in java

JSONArray resultArray = (JSONArray)resultObject;
String str = (resultArray.get(0).toString())

Now I have a string which is as follows

{
    "styleId": "2276730",
    "price": "$199.95",
    "originalPrice": "$199.95",
    "colorId": "401",
    "productName": "Mutiny",
    "productId": "8149427",
    "percentOff": "0%"
},

I want to have the value of price for each such array

I am a newbie to JSON. Can anyone help me with this?

3
  • 3
    The example "JSON" you've provided isn't an array (it's an object) and it's not even a valid object, because of the extra trailing comma. Please provide a complete example which reproduces the exact problem. Commented Feb 18, 2014 at 18:06
  • He said it's an item of JSONArray Commented Feb 18, 2014 at 18:09
  • 1
    You shouldn't do toString until you have the object you want (if then). Assuming the original is a JSONArray, get the element by number, cast the result to JSONObject, and then do get("price") on that. This should directly return a String containing the price. Commented Feb 18, 2014 at 18:12

1 Answer 1

1
JSONArray resultArray = (JSONArray) resultObject;
for (int i=0;i<resultArray.length();i++){
    JSONObject result = resultArray.getJSONObject(i);
    System.out.println(result.getString("price"));
}
Sign up to request clarification or add additional context in comments.

6 Comments

JSONObject result = array.getJSONObject(i); can I know what is array referring to here??
It was a typo, I've corrected it. Of course it should be resultArray
Yes.I too thought it was resultArray but when I am running the code, the ide is not identifyingthe getJSONObject method. I checked the imports but of no use. The method getString is also not being recognized. I ran the code and the error indicates the same.
Did you add "import org.json.JSONObject;" and "import org.json.JSONArray;" at the header of your file? getString is a valid method of JSONObject json.org/javadoc/org/json/…
Note that there are two entirely different and distinct JSON kits that use "JSONObject" and "JSONArray".
|

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.