parssing JSONException:一个JSONArray文本必须以'['人品1 [英] parssing JSONException: A JSONArray text must start with '[' at character 1

查看:356
本文介绍了parssing JSONException:一个JSONArray文本必须以'['人品1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想Android应用程序与本地MySQL数据库的连接,但是我有一个问题
解析JSON阵列。 (我在这里阅读所有类似的问题,但没有任何工程。)

错误消息:

 错误解析数据org.json.JSONException:一个JSONArray文本必须以[在性格1 [{\"UserName\":\"Admin\",\"Password\":\"111\",\"Role\":\"0\"},{\"UserName\":\"Employee\",\"Password\":\"123\",\"Role\":\"1\"}]

这是code中的:

 公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);    新的连接()执行();
}私有类连接扩展的AsyncTask<太虚,太虚,字符串> {
    私人字符串结果=;
    私人InputStream为= NULL;
    私人进度progress_Bar;    在preExecute保护无效(){
        progress_Bar =((进度)findViewById(R.id.progress));
        progress_Bar.setVisibility(0);
    }    @覆盖
    保护字符串doInBackground(虚空...... PARAMS){
        尝试{
            ArrayList的<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;();
            HttpClient的HttpClient的=新DefaultHttpClient();
            HttpPost httppost =新HttpPost(http://10.0.2.2/users.php);
            httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
            HTT presponse响应= httpclient.execute(httppost);
            HttpEntity实体= response.getEntity();
            是= entity.getContent();
        }赶上(例外五){
            Log.e(log_tag,在HTTP连接错误+ e.toString());
        }        //响应转换为字符串
        尝试{
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是,UTF-8),8);
            StringBuilder的SB =新的StringBuilder();
            串线= NULL;
            而((行= reader.readLine())!= NULL){
                sb.append(线);
            }
            is.close();
            结果= sb.toString();
            result.trim();        }赶上(例外五){
            Log.e(log_tag,错误转换结果+ e.toString());
        }        返回结果;
    }    保护无效onPostExecute(字符串结果){
        字符串名称;        尝试{
            Log.d(结果,结果);            JSONArray jArray =新JSONArray(结果);
            JSONObject的json_data = NULL;
            的for(int i = 0; I< jArray.length();我++){
                json_data = jArray.getJSONObject(ⅰ);                Toast.makeText(getApplicationContext(),,Toast.LENGTH_LONG).show();
            }
        }赶上(JSONException E){
            Log.e(log_tag,错误分析数据+ e.toString());
        }
    }
}

这是PHP code:

 < PHP
$ CON1 = mysql_connect(localhost的根,);mysql_select_db(sehaty);
的mysql_query(集名UTF8);$ SQL =的mysql_query(SELECT * FROM用户);
而($行= mysql_fetch_assoc($ sql中)){
    $输出[] = $行;
}
$数据= json_en code($输出);
打印($的数据);
mysql_close();
?>


解决方案

也许是因为有前/​​后间隔的数据无效/换行符/...

我想preprocess 结果 onPostExcecute(...)是这样的:

 私人最终静态字符串TAG =YourApplication;公共静态字符串asHex(字符串str)
{
    字节[] buf中= str.getBytes();
    最终的char [] HEX_CHARS =0123456789ABCDEF.toCharArray();
    的char [] =字符新的char [2 * buf.length]。
    的for(int i = 0; I< buf.length; ++ I)
    {
        字符[2 * i] = HEX_CHARS [(BUF [1] - 安培; 0XF0)GT;>> 4〕;
        字符[2 * I + 1] = HEX_CHARS [BUF [1] - 放大器;为0x0F];
    }
    返回新的String(字符);
}保护无效onPostExecute(字符串结果){
    尝试{
        结果= result.replaceAll([\\ n \\ t],).replaceAll([^ A-ZA-Z0-9 \\,\\ [\\] {}],).trim() ;
        Log.d(TAG,结果:#+结果+#);
        Log.d(TAG,结果:+ asHex(结果));        JSONArray jArray =新JSONArray(结果);
        的for(int i = 0; I< jArray.length();我++){
            Log.d(TAG,USERS:+ jArray.getJSONObject(I)的ToString());
        }
    }赶上(JSONException E){
        Log.e(TAG,ERROR:+ e.toString());
    }
}

I'm trying to connect Android app with local MySQL database, but I have a problem in parsing JSON array. (I read all similar questions here, but nothing works.)

the error message:

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"}] 

this is the the code:

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());
        }
    }
}

and this is the PHP code:

<?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();
?>

解决方案

Maybe your data is not valid because there are leading/trailing spaces/newlines/...

I would preprocess result in onPostExcecute(...) like this:

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());
    }
}

这篇关于parssing JSONException:一个JSONArray文本必须以'['人品1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆