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?

Floern
  • 33,559
  • 24
  • 104
  • 119
Ash
  • 671
  • 2
  • 7
  • 18

3 Answers3

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);
}
michoprogrammer
  • 1,159
  • 2
  • 18
  • 45
Ash
  • 682
  • 2
  • 10
  • 20
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);
Hariharan
  • 24,741
  • 6
  • 50
  • 54
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.

NightFury
  • 13,436
  • 6
  • 71
  • 120