Reputation: 5971
my app was working really nice with that json
{
"id":"1",
"title_en":"Civil War",
"artist_en":"MOTORHEAD"
}
but when i tried to add multiple songs like that
{
"song_list":[
{"id":"1",
"title_en":"Civil War",
"artist_en":"MOTORHEAD"},
{"id":"2",
"title_en":"Slide It In",
"artist_en":"WHITESNAKE"}]
}
it generates an exception, even before retrieving data
09-08 07:29:53.998: W/System.err(982): org.json.JSONException: Value ? of type java.lang.String cannot be converted to JSONObject
09-08 07:29:53.998: W/System.err(982): at org.json.JSON.typeMismatch(JSON.java:107)
09-08 07:29:53.998: W/System.err(982): at org.json.JSONObject.<init>(JSONObject.java:158)
09-08 07:29:53.998: W/System.err(982): at org.json.JSONObject.<init>(JSONObject.java:171)
09-08 07:29:53.998: W/System.err(982): at com.dwaik.jsonparser.JSONParser.getJSONObject(JSONParser.java:46)
09-08 07:29:53.998: W/System.err(982): at com.dwaik.myapp.CustomizedListView.onCreate(CustomizedListView.java:48)
additional info : the parser
public JSONObject getJSONObject(InputStream inputStream)
{
String result = null;
JSONObject jObject = null;
try
{
// json is UTF-8 by default
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
result = sb.toString();
jObject = new JSONObject(result);
}
catch (JSONException e)
{
e.printStackTrace();
return null;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
finally
{
try
{
if (inputStream != null)
inputStream.close();
}
catch (Exception e)
{
}
}
return jObject;
}
and its call
final JSONObject jObject = (new JSONParser(this)).getJSONObject(getResources().openRawResource(R.raw.sample));
Upvotes: 2
Views: 1837
Reputation: 574
From a quick glance, you are trying to convert the entire string into a JsonObject, however, it is not a JsonObject, it's actualy a JsonArray containing multiple JsonObject's.
here's a small code snippet to guide you through a similar process of parsing a json string containing an array of json's :
public ArrayList<Ride> parse (String str) throws JSONException
{
ArrayList<Ride> rides = new ArrayList<Ride>();
try{
JSONArray ridesJsonArray = new JSONArray(str);
Ride ride;
for (int i=0;i<ridesJsonArray.length();i++)
{
ride = new Ride();
JSONObject o = ridesJsonArray.optJSONObject(i);
ride.rideId=o.optInt("id");
ride.fullName=o.optString("fullname");
ride.origin=o.optString("origin");
ride.destination=o.optString("destination");
ride.date=o.optString("date");
ride.time=o.optString("time");
ride.phone=o.optString("phone");
ride.email=o.optString("email");
ride.comments=o.optString("comments");
//log message to make sure the rides are coming from the server
Log.i("Rides", ride.fullName + " | ");
rides.add(ride);
}
return rides;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
Upvotes: 3