我的应用程序与json
工作得非常好{
"id":"1",
"title_en":"Civil War",
"artist_en":"MOTORHEAD"
}
但当我尝试添加多首歌曲时
{
"song_list":[
{"id":"1",
"title_en":"Civil War",
"artist_en":"MOTORHEAD"},
{"id":"2",
"title_en":"Slide It In",
"artist_en":"WHITESNAKE"}]
}
它甚至在检索数据之前就会生成异常
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)
其他信息:解析器
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;
}
及其电话
final JSONObject jObject = (new JSONParser(this)).getJSONObject(getResources().openRawResource(R.raw.sample));
答案 0 :(得分:3)
从快速浏览一下,您试图将整个字符串转换为JsonObject,但是,它不是JsonObject,它实际上是一个包含多个JsonObject的JsonArray。
这是一个小代码片段,引导您完成解析包含json数组的json字符串的类似过程:
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;
}
}