我的Android应用程序抛出JSONException,但我无法弄清楚原因! 我正在使用一个php页面从MYSQL数据库中选择一些列并将它们放入这样的数组中:
$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();
}
然后我有一个带有onpostexecute方法的Asynctask类,如下所示:
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();
}
}
我很感激有关此事的任何帮助
答案 0 :(得分:0)
如何解析de JSON?
您需要使用try/catch
方法!
我使用这样的东西:
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
//Code for getting objects/arrays
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}