解析JSONException:JSONArray文本必须以字符1处的'['开头

时间:2012-03-24 19:11:50

标签: android mysql

我正在尝试将Android应用与本地MySQL数据库连接,但我遇到了问题 解析JSON数组。 (我在这里阅读了所有类似的问题,但没有任何效果。)

错误消息:

Error parsing data org.json.JSONException: A JSONArray text must start with '[' at character 1 of [{"UserName":"Admin","Password":"111","Role":"0"},{"UserName":"Employee","Password":"123","Role":"1"}] 

这是代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    new Connect().execute();
}

private class Connect extends AsyncTask<Void, Void, String> {
    private String result = "";
    private InputStream is = null;
    private ProgressBar progress_Bar;

    protected void onPreExecute() {
        progress_Bar = ((ProgressBar) findViewById(R.id.progress));
        progress_Bar.setVisibility(0);
    }

    @Override
    protected String doInBackground(Void... params) {
        try {
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/users.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            is.close();
            result = sb.toString();
            result.trim();

        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        return result;
    }

    protected void onPostExecute(String result) {
        String name;

        try {
            Log.d("RESULT", result);

            JSONArray jArray = new JSONArray(result);
            JSONObject json_data = null;
            for (int i = 0; i < jArray.length(); i++) {
                json_data = jArray.getJSONObject(i);

                Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
    }
}

这是PHP代码:

<?php
$con1=mysql_connect("localhost", "root", "");

mysql_select_db("sehaty");
mysql_query("SET NAMES utf8"); 

$sql = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_assoc($sql)) {
    $output[]=$row;
}
$data = json_encode($output);
print($data);
mysql_close();
?>

4 个答案:

答案 0 :(得分:0)

你发布的json是有效的。问题可能与您从输入流中读取的方式有关

尝试更改此

try{
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line);
    }

    int read = 0;
    int  BUFFER_LEN = 32768;
    byte[] buffer = new byte[BUFFER_LEN];
    while ( (read = is.read(buffer, 0, BUFFER_LEN)) >= 0) {
        sb.append(new String(buffer, 0, read));
    }

    is.close();

答案 1 :(得分:0)

尝试使用我的部分代码:

// Execute HTTP Post Request

HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder();

String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); }

is.close(); result=sb.toString();

JSONArray jArray = new JSONArray(result); JSONObject json_data= new JSONObject();

for(int i=0;i<jArray.length();i++){ json_data = jArray.getJSONObject(i); }

答案 2 :(得分:0)

试试这个:

请求代码中的第一个:

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            result = out.toString();

和int解析:

        JSONArray jArray = new JSONArray(result);
        JSONObject json_data = null;
        String s = "";
        for (int i = 0; i < jArray.length(); i++) {
            s = jArray.get(i).toString();
            json_data = new JSONObject(s);

            Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show();
        }

尝试将结果JSON设置为“{result:[{”UserName“:”Admin“,”Password“:”111“,”Role“:”0“},{”UserName“:”Employee“ ,“Passwo rd”:“123”,“角色”:“1”},{“UserName”:“x”,“密码”:“x”,“角色”:“ - 1”}]}“和在解析中:

    JSONObject json = new JSONObject(result);
    JSONArray jArray = json.getJSONArray("result");
    JSONObject json_data = null;
    String s = "";
    for (int i = 0; i < jArray.length(); i++) {
        s = jArray.get(i).toString();
        json_data = new JSONObject(s);

        Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show();
    }

答案 3 :(得分:0)

也许您的数据无效,因为有前导/尾随空格/换行符/...

我会在result中预处理onPostExcecute(...),如下所示:

private final static String TAG = "YourApplication";

public static String asHex(String str)
{
    byte[] buf = str.getBytes();
    final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
    char[] chars = new char[2 * buf.length];
    for (int i = 0; i < buf.length; ++i)
    {
        chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
        chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
    }
    return new String(chars);
}

protected void onPostExecute(String result) {
    try {
        result = result.replaceAll("[\n\t]", "").replaceAll("[^ A-Za-z0-9\",\[\]{}]", "").trim();
        Log.d(TAG, "RESULT: #" + result + "#");
        Log.d(TAG, "RESULT: " + asHex(result));

        JSONArray jArray = new JSONArray(result);
        for (int i = 0; i < jArray.length(); i++) {
            Log.d(TAG, "USERS: " + jArray.getJSONObject(i).toString());
        }
    } catch (JSONException e) {
        Log.e(TAG, "ERROR: " + e.toString());
    }
}