Shweta Shweta - 5 months ago 12
JSON Question

How to convert json object into string in Android

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?

Answer

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);
                }
Comments