I am new to JSON
and I am getting the follwoing Exception:
org.json.JSONArray cannot be converted to JSONObject
in the first line of try se
This
JSONObject json = new JSONObject(strResponse);
// your strResponse is a json array
should be
JSONArray jsonarray = new JSONArray(strResponse);
[
represents json array node
{
represents json object node
for(int i=0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String id = jsonobject.getString("id");
String title = jsonobject.getString("title");
String company = jsonobject.getString("company");
String category = jsonobject.getString("category");
}
You should probably initialize json
as a JSONArray
:
JSONObject json = new JSONObject(strResponse);
Should then be:
JSONArray json = new JSONArray(strResponse);
However, that wouldn't work with the following two operations:
JSONArray name = json.names(); //.names() doesn't exist in JSONArray
JSONArray internships = json.toJSONArray(name); // Is instead to be seen as
That would be alright if you just alter your loop to get the JSONObject
from json
instead (thus removing the dependency towards .names()
:
JSONObject e = json.getJSONObject(i);
Edit: Full code
try {
JSONArray internships = new JSONArray(strResponse);
//Loop the Array
for(int i=0;i < internships.length();i++) {
Log.e("Message","loop");
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = internships.getJSONObject(i);
map.put("id", String.valueOf("id"));
map.put("title", "Title :" + e.getString("title"));
map.put("company", "Company : " + e.getString("company"));
map.put("category", "Category : " + e.getString("category"));
mylist.add(map);
}
} catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
try this one , Your first block is json array so get first json array
JSONArray jsonarray = new JSONArray(strResponse);
for(int i=0;i < jsonarray .length();i++) {
JSONObject jsonobj = new JSONObject(i);
map.put("id", jsonobj .getString("id"));
map.put("title", jsonobj .getString("title"));
map.put("company", jsonobj .getString("company"));
map.put("category", jsonobj .getString("category"));
mylist.add(map);
}
if that really is the json you are receiving you should replace the entire this:
JSONObject json = new JSONObject(strResponse);
//Get the element that holds the internship ( JSONArray )
JSONArray name = json.names();
JSONArray internships = json.toJSONArray(name);
with
JSONArray internships = json.toJSONArray(strResponse);
Issue:
JSONObject json = new JSONObject(strResponse);
here, strResponse
may be in format of JSONArray
due to which you are getting this exception while converting it into JSONObject
.