首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >org.json.JSONException:状态没有值

org.json.JSONException:状态没有值
EN

Stack Overflow用户
提问于 2018-05-30 07:17:35
回答 1查看 606关注 0票数 -2

org.json.JSONException:状态没有值

下面是我用于json解析的java代码方法

java

代码语言:javascript
复制
public void performSearch() {
            String url= "http://192.168.0.136/fyp/stitle1.php";
            RequestQueue requestQueue = Volley.newRequestQueue(Stitle.this);
           JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,url,null,
                   new Response.Listener<JSONObject>() {
               @Override
               public void onResponse(JSONObject response) {
                   Log.d("Response", response.toString());
                   try {
                       //converting the string to json array object
                       JSONObject array = new JSONObject();
                       //Log.i("test", " value : " + array.getString("status"));
                       Log.i("test", " value : " + response.getString("status"));
                       if (array.getString("status").equals("true")) {
                           JSONArray jsonArray = array.getJSONArray("search");
                           Log.i("test", " value : " + array);

                           for (int i = 0; i < jsonArray.length(); i++) {

                               //getting product object from json array
                               JSONObject product = jsonArray.getJSONObject(i);

                               //adding the product to product list
                               boolean add = productList.add(new list(
                                       product.getLong("isbn"),
                                       product.getString("title"),
                                       product.getString("authors"),
                                       product.getInt("accession"),
                                       product.getString("publisher"),
                                       product.getInt("pubyear"),
                                       product.getInt("pages"),
                                       product.getInt("rak"),
                                       product.getInt("hr"),
                                       product.getInt("vr"),
                                       product.getLong("barcode")

                               ));

                           }

                       } else {
                           Log.i("test", "else error");

                       }


                   } catch (JSONException e) {
                       e.printStackTrace();
                       Log.i("test", e.toString());
                   }
               }

           }, new Response.ErrorListener() {
               @Override
               public void onErrorResponse(VolleyError error) {
                   Toast.makeText(getApplicationContext(), "error:" + error.toString(), Toast.LENGTH_LONG).show();

               }
           }) {
               @Override
               protected Map<String, String> getParams() throws AuthFailureError {

                   Map<String, String> params = new HashMap<>();
                   params.put("Title", searchtitle.getText().toString());

                   return params;
               }
           };
           requestQueue = Volley.newRequestQueue(Stitle.this);
           requestQueue.add(jsObjRequest);

        }

将参数传递给android jsonobject的Php文件

stitle1.php

php

代码语言:javascript
复制
<?php

 // array for JSON response
   $response = array();
  //set values just in case any thing goes wrong
  $response["status"] = 0;
 $response["message"] = "Error before start";

// check for post data with isset
 if (isset($_POST["Title"])) {

$title = $_POST["Title"];

// You were not using PDO so I dumped your connection and require you to provide...
//...a configuration file for ...
require_once 'connection.php';
// ...these  variables
$host = 'localhost';
$db   = 'fyp';
$user = 'root';
$pass = '';
$charset = 'utf8';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try{
    // connecting to db with PDO
    $pdo = new PDO($dsn, $user, $pass, $opt);


    $sql = 'SELECT isbn, title, authors, accession, publisher, pubyear, pages, rak, hr, vr, barcode
            FROM books 
            WHERE title LIKE :titleParam';

    $titleParam = "%".$title."%";

    $stmt = $pdo->prepare($sql);

    // Bind the parameter
    $stmt->bindParam(':titleParam', $titleParam, PDO::PARAM_STR);

    $res = $stmt->execute();

    if ($res) {
        // success
        $response["status"] = 1;
        // connection node
        $response["books"] = array();

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $data = array();
            $data["isbn"] = $row["isbn"];
            $data["title"] = $row["title"];
            $data["authors"] = $row["authors"];
            $data["accession"] = $row["accession"];
            $data["publisher"] = $row["publisher"];
            $data["pubyear"] = $row["pubyear"];
            $data["pages"] = $row["pages"];
            $data["rak"] = $row["rak"];
            $data["hr"] = $row["hr"];
            $data["vr"] = $row["vr"];
            $data["barcode"] = $row["barcode"];

            array_push($response["books"], $data);
        }
    }
    else {
        // required field is missing
        $response["status"] = 2;
        $response["message"] = "No data returned";
    }   
}
catch (Exception $e){
    $response["status"] = 3;
    $response["message"] = "Error occurred." . $e->getMessage();
    }
  }
   else {
      $response["status"] = 4;
        $response["message"] = "Post parameters are not correct";
    }
      // echoing JSON response
      echo json_encode($response);
    ?>

当我运行我的应用程序时,这些线条出现在logcat面板上

I/test:值:4

I/test: org.json.JSONException:无状态值

这两行出现在logcat上,指示有关参数未正确发送的错误

EN

回答 1

Stack Overflow用户

发布于 2018-05-30 07:24:54

我们将一步一步地走。让我们从响应开始。

您的PHP值返回一个status值=4,这表明您没有正确地获得发送到PHP代码的参数。有可能getParams()甚至没有被调用。

代码语言:javascript
复制
@Override
protected Map<String, String> getParams() throws AuthFailureError {
    Map<String, String> params = new HashMap<>();
    try{
        String s = searchtitle.getText().toString();
        Log.e("Volley request", "getParams called : " + s);
        params.put("Title", s);
    }
    catch(Exception ex){
        Log.e("Volley request ERROR", ex.getMessage());
    }
    return params;
}

对于第二部分,让我们尝试处理解析代码。将代码更改为如下所示:

现在,不管你的php代码如何响应,你都会得到一个格式良好的JSONObject作为响应,你可以对它进行适当的解析和反应。

更改代码的onResponse()部分,如下所示:

代码语言:javascript
复制
@Override
public void onResponse(JSONObject response) {
    // Log.d("Response", response.toString());
    try {
        //converting the string to json array object
        if(response != null){
            if(!response.has("status"){
                Log.e(TAG, "Something went wrong -- no status key!");
                return;
            }
            else{
                int status = response.optInt("status", -1);
                if(status == 1){
                    //There could be quite a few books in this response...
                    //...you might want to parse in an AsyncTask instead
                    parseJsonObject(response);
                }
                else{
                    String message = response.optString("message", "uups");
                    Log.e(TAG, "error message = " + message);
                    return;
                }
            }
        }
    }
    catch(Exception ex){
        Log.e(TAG, ex.getMessage());
    }
}

代码语言:javascript
复制
Map<String, String> booksMap = new HashMap<>();

    private void parseJsonObject(JSONObject jsonObject){
        try{
            if(jsonObject == null) return;
            //Not Available!
            String na = "NA"

            Log.i("test", " value : " + jsonObject.toString());
            if(jsonObject.has("books")){
                JSONArray array = jsonObject.getJSONArray("books");
                for(int i = 0; array.length(); i++){
                    JSONObject book = array.getJSONObject(i);
                    Iterator<String> it = book.keys();
                    while(it.hasNext()){
                        String key = it.next();
                        String value = book.optString(key, na);
                        booksMap.put(key, value);
                    }
                }
            }
        }
        catch(Exception ex){
            Log.e(TAG, ex.getMessage());
        }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50594284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档