我的android應用程序拋出JSONException,但我找不出原因! 我使用的是PHP頁面,從一個MySQL數據庫中選擇部分列並把它們放入一個這樣的數組:獲取JSONException的Android應用程序
$sql = "SELECT name,type,price FROM $tbname";
$result = $conn->query($sql);
$jsonarray=array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$jsonarray[]=$row;
}
$myJSON = json_encode($jsonarray);
echo $myJSON;
導致這樣的JSON:
[{"name":"sandwich","type":"food","price":"5000"},{"name":"pizza","type":"food","price":"10000"}]
但是當我嘗試在Android Studio中解析上述JSON時,會引發JSONException。 我的Java代碼: 我有在課堂上發送數據的方法稱爲httpmanager如下:
public static String SendData(DataPack pack) throws IOException {
URL url=new URL(pack.getUri());
BufferedReader reader=null;
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter w=new OutputStreamWriter(connection.getOutputStream());
w.write(pack.Encode());
w.flush();
StringBuilder sb=new StringBuilder();
reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line=reader.readLine())!=null){
sb.append(line + "\n");
}
return sb.toString();
}
然後人工智能擁有的AsyncTask類這樣的onpostexecute方法:
protected void onPostExecute(String s) {
String jsonStr = s;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
Toast.makeText(context, "JSON recieved!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
我會很感激任何關於此事的幫助
後您的Android代碼... JSON解析 – rafsanahmad007
您的JSON似乎有效的。發佈你的logcat和解析代碼 –
你如何解析JSON?你能發佈你的Java代碼嗎? – BlackHatSamurai