-2

我收到以下错误:

Error parsing to json on getJarrayFromString(); org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONArray

我的 JSON 代码如下:

public String getJsonFromUrl(String url){

        // to initialise the objects
        InputStream is = null;
        String result = "";

        //making HTTP POST request
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }catch(Exception e){
            Log.e(DEBUG, "Error getJsonFromUrl: " + e.toString());
        }

        // Converting to String
        try{
            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();
        }catch(Exception e){
            Log.e(DEBUG, "Error converting the response to string getJsonFromUrl: " + e.toString());
        }

        return result;
    }

    /**
     * To convert the string recieved into json object
     * result refers to the string that will be converted
     * @return will return the json array
     */
    public JSONArray getJarrayFromString(String result){
        // Parsing string to JSON Array
        try{
            jarray = new JSONArray("result");                     <---- Error is here
        }catch(JSONException e){
            Log.e(DEBUG, "Error parsing to json on getJarrayFromString(); " + e.toString());
        }

        return jarray;
    }

我的 Java 活动如下:

public void onTaskCompleted(String result) {
                        try {  
                            if(result!=""){
                                // the remote php link 
                                // converting the response into json array
                                Log.i(DEBUG, result);
                                jarray = utils.getJarrayFromString(result);

                                // number of rows in total for a query
                                int mysqlSize = (jarray.getJSONObject(0).getInt("numRows"));

                                Log.i(DEBUG, "From " + from + " to " + mysqlSize);

                                // to check if all the rows are parsed from the mysql
                                if(from <= mysqlSize){
                                    int rows;
                                    // to check if there is 0
                                    if(jarray.length()>0){
                                        Log.i(DEBUG, "From " + from + " to " + Math.floor(mysqlSize/nr)*nr);
                                        if(from+5<=Math.floor(mysqlSize/nr)*nr){
                                            rows = jarray.length();
                                        }else{
                                            rows = mysqlSize%nr+1;
                                            Utils.IS_ENDED_PRODUCT_LIST = true;
                                        }
                                        ArrayList<String> list = new ArrayList<String>();
                                        for(int i=1; i<rows; i++){
                                            JSONObject row = jarray.getJSONObject(i);
                                            bid.add(row.getInt("bid"));
                                            bTitle.add(row.getString("bTitle"));
                                            bCode.add(row.getString("bCode"));
                                            bPrice.add(row.getString("bPrice") + "£");
                                            bDescription.add(row.getString("bDescription"));
                                            bModule.add(row.getString("bModule"));
                                            bImage.add(Utils.PATH + row.getString("bImage"));
                                            list.add(row.getString("bImage"));
                                            // to check if an id already exists in the db or to create one if doesn't exist
                                            if(!db.hasIDBooks(row.getInt("bid"))) db.createRowOnBooks(row.getInt("bid"), row.getString("bTitle"), row.getString("bCode"), row.getString("bPrice"), row.getString("bDescription"), row.getString("bModule"), Utils.PATH + row.getString("bImage"), row.getString("bSpecialOffer"), row.getInt("bSpecialDiscount"), row.getString("bDateAdded"));
                                            Log.i(DEBUG, row.getString("bDescription"));
                                        }
                                        new DownloadImages(list, bAdapter).execute();
                                    }
                                }
                                postParameters.removeAll(postParameters);
                            }else{
                                Utils.IS_ENDED_PRODUCT_LIST = true;
                                if(rlLoading.isShown()){
                                    rlLoading.startAnimation(fadeOut());
                                    rlLoading.setVisibility(View.INVISIBLE);
                                }
                            }
                        } catch (Exception e) {  
                            Log.e(DEBUG, "Error at fillProductList(): " + e.toString());  
                        }
                    }
                });
                task.execute();

        }else{
            // if internet connectio is not available
            // then, rows will be fetched from the local sqllite database stored on the android phone
            if(db.size(justdealsDatabase.TABLE_BOOKS) > 0){
                Cursor cursor = db.getBooksRows(justdealsDatabase.TABLE_BOOKS);
                cursor.moveToFirst();
                while(!cursor.isAfterLast()){
                    bid.add(cursor.getInt(cursor.getColumnIndex(justdealsDatabase.KEY_BID)));
                    bTitle.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BTITLE)));
                    bCode.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BCODE)));
                    bPrice.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BPRICE))+ "£");
                    bDescription.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BDESCRIPTION)));
                    bModule.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BMODULE)));
                    bImage.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BIMAGE)));
                    cursor.moveToNext();
                }
                bAdapter.notifyDataSetChanged();
                Utils.IS_ENDED_PRODUCT_LIST = true;
            }
        }
    }

最后,我上面代码的 PHP API 在这里:

 <?php
    include("MysqlConnection.php");
    header('Content-Type: application/json');
    $from = $_POST["from"];
    $nr = $_POST["nr"];
    // those variables are for search
    $title = $_POST["title"];
    $code = $_POST["code"];
    $price = $_POST["price"];
    $module = $_POST["module"];
    $order = $_POST["order"];
    $by = $_POST["by"];


    $sql = "SET CHARACTER SET utf8";
    $db->query($sql);


        // if those 2 var are set then we order the query after them
        if(isset($order) && isset($by)){
            $sql .= " ORDER BY `$order` $by LIMIT $from, $nr";
        }else{
            $sql .= "LIMIT $from, $nr";
        }

        $query = $db->query($sql);
        $rows = array();
        $rows[] = array("numRows"=>$db->numRows($query));

        if($db->numRows($query)!=0){
            while($row = mysql_fetch_assoc($query)) {
                $rows[] =  $row;
            }
            echo(json_encode($rows));
        }
    }

    $db->closeConnection();
?>

现在我已经对这个主题进行了广泛的研究,但无法找到上述问题的具体解决方案。

我读过一些帖子,这些帖子可能是在不使用双引号的情况下声明的字符串。这是否意味着存储在 SQL 文件中的值(例如书名、价格等)需要使用双引号而不是单引号?

如果我在 JSONLint 中运行上述代码,则会收到以下错误:

Parse error on line 1:

^
Expecting '{', '['

我尝试使用 ("{result}") 代替 {result) 或 ("result") 但这给了我更多错误。我非常接近让整个应用程序工作,但唯一的问题是将result字符串转换为有效的 JSON 数组。

任何想法和建议将不胜感激。

执行 JARRAY= 新 JSONARRAY(结果)后编辑的 LOG CAT 错误;

03-06 21:17:31.387: D/AndroidRuntime(818): Shutting down VM
03-06 21:17:31.387: W/dalvikvm(818): threadid=1: thread exiting with uncaught exception (group=0x40014760)
03-06 21:17:31.417: E/AndroidRuntime(818): FATAL EXCEPTION: main
03-06 21:17:31.417: E/AndroidRuntime(818): java.lang.NullPointerException
03-06 21:17:31.417: E/AndroidRuntime(818):  at com.fokrul.justdeals.ActivityTab$ProductsAdapter.getView(ActivityTab.java:1565)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.AbsListView.obtainView(AbsListView.java:1970)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.ListView.makeAndAddView(ListView.java:1756)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.ListView.fillDown(ListView.java:656)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.ListView.fillFromTop(ListView.java:716)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.ListView.layoutChildren(ListView.java:1595)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.AbsListView.onLayout(AbsListView.java:1800)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.RelativeLayout.onLayout(RelativeLayout.java:912)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.FrameLayout.onLayout(FrameLayout.java:400)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1542)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1403)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.LinearLayout.onLayout(LinearLayout.java:1314)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.FrameLayout.onLayout(FrameLayout.java:400)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.RelativeLayout.onLayout(RelativeLayout.java:912)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.FrameLayout.onLayout(FrameLayout.java:400)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1542)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1403)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.LinearLayout.onLayout(LinearLayout.java:1314)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.widget.FrameLayout.onLayout(FrameLayout.java:400)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.View.layout(View.java:9581)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.ViewGroup.layout(ViewGroup.java:3877)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.ViewRoot.performTraversals(ViewRoot.java:1282)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.view.ViewRoot.handleMessage(ViewRoot.java:2040)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.os.Looper.loop(Looper.java:132)
03-06 21:17:31.417: E/AndroidRuntime(818):  at android.app.ActivityThread.main(ActivityThread.java:4123)
03-06 21:17:31.417: E/AndroidRuntime(818):  at java.lang.reflect.Method.invokeNative(Native Method)
03-06 21:17:31.417: E/AndroidRuntime(818):  at java.lang.reflect.Method.invoke(Method.java:491)
03-06 21:17:31.417: E/AndroidRuntime(818):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
03-06 21:17:31.417: E/AndroidRuntime(818):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
03-06 21:17:31.417: E/AndroidRuntime(818):  at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

0

这部分在这里

jarray = new JSONArray("result"); 

当然应该阅读

jarray = new JSONArray(result); 

相反,但我想你已经尝试过了。从解析器错误来看,我假设结果根本不包含有效的 JSON 字符串。如果它应该表示一个数组,它必须是这样的(以最简单的形式):

["abc", "def", "ghi"]

当涉及到单引号或双引号时,一些 JSON 解析器很挑剔。但在你的情况下,问题似乎在于括号。您能否使用调试器进入getJarrayFromString并检查进入 getJarrayFromString 的结果值是什么或者至少将原始值打印到控制台?

于 2013-03-06T20:57:13.943 回答