1

My JSON format is:

[
    {
        "change": 1.59,
        "name": "ABC",
        "price": 10.52,
        "volume": 230
    },
    {
        "change": -0.05,
        "name": "DEF",
        "price": 1.06,
        "volume": 1040
    },
    {
        "change": 0.01,
        "name": "GHI",
        "price": 37.17,
        "volume": 542
    }
]

I want to parse it and convert it into string. I am using this method for converting it:

JSONObject jsonObj = new JSONObject(jsonStr);
for (int i = 0; i < jsonObj.length(); i++)
{                                              
    String change = jsonObj.getString(TAG_CHANGE);
    String name = jsonObj.getString(TAG_NAME);
    String price = jsonObj.getString(TAG_PRICE);
    String volume = jsonObj.getString(TAG_VOLUME);
    HashMap<String, String> contact = new HashMap<String, String>();

    // adding each child node to HashMap key => value
    contact.put(TAG_CHANGE, change);
    contact.put(TAG_NAME, name);
    contact.put(TAG_PRICE, price);
    contact.put(TAG_VOLUME, volume);

    // adding contact to contact list
    contactList.add(contact);
}

But I get an error:

/System.err(867): at org.json.JSON.typeMismatch(JSON.java:111)

How do I resolve this?

3 Answers 3

1

Please try it, It should work

JSONArray jsonObj = new JSONArray(jsonStr);

for (int i = 0; i < jsonObj.length(); i++) {
    JSONObject c = jsonObj.getJSONObject(i);
    String change = c.getString(TAG_CHANGE);
    String name = c.getString(TAG_NAME);
    String price = c.getString(TAG_PRICE);
    String volume = c.getString(TAG_VOLUME);
    HashMap < String, String > contact = new HashMap < String, String > ();
    contact.put(TAG_CHANGE, change);
    contact.put(TAG_NAME, name);
    contact.put(TAG_PRICE, price);
    contact.put(TAG_VOLUME, volume);
    contactList.add(contact);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this..

You are getting response as JSONArray but you are doing it as JSONObject

[                // this is JSONArray
      {          // this is JSONObject

Change this

JSONObject jsonObj = new JSONObject(jsonStr);

to

JSONArray jsonObj = new JSONArray(jsonStr);

Comments

0

You are parsing in wrong way. your json is starts with an array containing JsonObjects. This can be identified since square braces denote JsonArray while curly braces denote JsonObject. Start with:

JSONArray jsonArr = new JSONArray(jsonStr);

then iterate through each object, get JsonObject at each index and use getString method for each key to get values.

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.