Android Studio:org.json.JSONArray 类型无法转换为 JSONObject

Posted

技术标签:

【中文标题】Android Studio:org.json.JSONArray 类型无法转换为 JSONObject【英文标题】:Android Studio: type org.json.JSONArray cannot be converted to JSONObject 【发布时间】:2020-03-04 16:05:14 【问题描述】:

我想创建列表视图。我指的是https://demonuts.com/android-listview-using-volley/。

我只得到android的源代码,而不是php。当我创建自己的 php 文件时,应用程序会继续显示加载并且永不停止。看到log cat的时候显示“type org.json.JSONArray cannot be convert to JSONObject”

下面是代码

MainActivity.java

   protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    listView = findViewById(R.id.lv);

    retrieveJSON();



private void retrieveJSON() 

    showSimpleProgressDialog(this, "Loading...","Fetching Json",false);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, URLstring,
            new Response.Listener<String>() 
                @Override
                public void onResponse(String response) 

                    Log.d("strrrrr", ">>" + response);

                    try 

                        JSONObject obj = new JSONObject(response);
                        if(obj.optString("status").equals("true"))

                           dataModelArrayList = new ArrayList<>();
                            JSONArray dataArray  = obj.getJSONArray("data");

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

                                DataModel playerModel = new DataModel();
                                JSONObject dataobj = dataArray.getJSONObject(i);

                                playerModel.setTitle(dataobj.getString("title"));
                                playerModel.setShortdesc(dataobj.getString("shortdesc"));
                                playerModel.setImage(dataobj.getString("image"));

                                dataModelArrayList.add(playerModel);

                            

                            setupListview();

                        

                     catch (JSONException e) 
                        e.printStackTrace();
                    
                
            ,
            new Response.ErrorListener() 
                @Override
                public void onErrorResponse(VolleyError error) 
                    //displaying the error in toast if occurrs
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                
            );

    // request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    requestQueue.add(stringRequest);




private void setupListview()
    removeSimpleProgressDialog();  //will remove progress dialog
    listAdapter = new ListAdapter(this, dataModelArrayList);
    listView.setAdapter(listAdapter);


public static void removeSimpleProgressDialog() 
    try 
        if (mProgressDialog != null) 
            if (mProgressDialog.isShowing()) 
                mProgressDialog.dismiss();
                mProgressDialog = null;
            
        
     catch (IllegalArgumentException ie) 
        ie.printStackTrace();

     catch (RuntimeException re) 
        re.printStackTrace();
     catch (Exception e) 
        e.printStackTrace();
    



public static void showSimpleProgressDialog(Context context, String title,
                                            String msg, boolean isCancelable) 
    try 
        if (mProgressDialog == null) 
            mProgressDialog = ProgressDialog.show(context, title, msg);
            mProgressDialog.setCancelable(isCancelable);
        

        if (!mProgressDialog.isShowing()) 
            mProgressDialog.show();
        

     catch (IllegalArgumentException ie) 
        ie.printStackTrace();
     catch (RuntimeException re) 
        re.printStackTrace();
     catch (Exception e) 
        e.printStackTrace();
    

recyclerview.php

<?php 

//database constants
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'recyclerview');

//connecting to database and getting the connection object
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

//Checking if any error occured while connecting
if (mysqli_connect_errno()) 
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    die();


//creating a query
$stmt = $conn->prepare("SELECT id, title, shortdesc, image FROM products;");

//executing the query 
$stmt->execute();

//binding results to the query 
$stmt->bind_result($id, $title, $shortdesc, $image);

$products = array(); 

//traversing through all the result 
while($stmt->fetch())
    $temp = array();
    $temp['id'] = $id; 
    $temp['title'] = $title; 
    $temp['shortdesc'] = $shortdesc; 
    $temp['image'] = $image; 
    array_push($products, $temp);


//displaying the result in json format 
echo json_encode($products);

?>

【问题讨论】:

【参考方案1】:

您的服务器脚本的当前版本生成以下格式的 JSON 响应。

[
   
      "id": 123,
      "title": "some title",
      "shortdesc": "description here",
      "image": "image here"
   ,
   
      "id": 124,
      "title": "some other title",
      "shortdesc": "description here",
      "image": "image here"
   
]

JSONArray 不是 JSONObject。然而,在您的 Android 应用代码中,您期望得到如下所示的 JSON 响应,


    "status": "true",
    "data": [
        
            "id": 123,
            "title": "some title",
            "shortdesc": "description here",
            "image": "image here"
        ,
        
            "id": 124,
            "title": "some other title",
            "shortdesc": "description here",
            "image": "image here"
        
    ]

在PHP代码中只需做如下调整,

<?php 

// other code here ...

//traversing through all the result 
while($stmt->fetch())
    $temp = array();
    $temp['id'] = $id; 
    $temp['title'] = $title; 
    $temp['shortdesc'] = $shortdesc; 
    $temp['image'] = $image; 
    array_push($products, $temp);



// create an array and add required key-values

$response = array();
$response["status"] = "true";
$response["data"] = $products;

//displaying the result in json format 
// pass $response array to json_encode() method

echo json_encode($response);

?>

【讨论】:

以上是关于Android Studio:org.json.JSONArray 类型无法转换为 JSONObject的主要内容,如果未能解决你的问题,请参考以下文章

android studio setting 在哪

如何解决android studio2.3导入android studio2.1的问题

Android studio上找不到setting?

android studio v4包冲突

如何用android studio 编成app

如何手动升级android studio?