org.json.JSONArray 无法转换为 JSONObject

org.json.JSONArray cannot be converted to JSONObject

我是 android 的新手,我正在使用 json 获取数据,但出现此错误 org.json.JSONArray cannot be converted to JSONObject.How followed this解决方案,但我仍然收到错误

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class MainActivity extends ActionBarActivity {

    String myJSON;

    private static final String TAG_RESULTS="result";
    private static final String TAG_USERNAME="username";
    private static final String TAG_NAME = "message_recd";
    private static final String TAG_ADD ="message_sent";

    JSONArray peoples = null;

    ArrayList<HashMap<String, String>> personList;

    ListView list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list = (ListView) findViewById(R.id.listView);
        personList = new ArrayList<HashMap<String,String>>();
        getData();

    }


    protected void showList(){
        try {
            JSONArray peoples = new JSONArray(myJSON);
            for(int i=0;i<peoples.length();i++){
                JSONObject c = peoples.getJSONObject(i);
                String name=null, address=null, username=null;

                if(c.has("message_recd"))
                    name = c.getString("message_recd");
                else if(c.has("message_sent"))
                    address = c.getString("message_sent");
               HashMap<String,String> persons = new HashMap<String,String>();
                persons.put(TAG_NAME,name);
                persons.put(TAG_ADD,address);
                personList.add(persons);
            }

            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, personList, R.layout.list_item,
                    new String[]{TAG_NAME,TAG_ADD},
                    new int[]{R.id.name, R.id.address}
            );

            list.setAdapter(adapter);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void getData(){
        class GetDataJSON extends AsyncTask<String, Void, String>{





            @Override
            protected String doInBackground(String... params) {

                Intent intent1 = getIntent();
                String fName = intent1.getStringExtra("fname");

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("username", fName));
                DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                HttpPost httppost = new HttpPost("http://10.0.2.2/progress_card/testing.php");

                 // Depends on your web service
                httppost.setHeader("Content-type", "application/json");

                InputStream inputStream = null;
                String result = null;
                try {
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();

                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    // Oops
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result){
                myJSON=result;
                showList();
            }
        }
        GetDataJSON g = new GetDataJSON();
        g.execute();
    }


}

Logcat:

09-22 06:45:38.035: W/System.err(6513): org.json.JSONException: Value [{"message_recd":"asdadasda"},{"message_recd":"hello"},{"message_recd":"how r u"},{"message_recd":"hello\n"},{"message_recd":"hello"},{"message_recd":"1"},{"message_recd":"qd"},{"message_recd":"1"},{"message_recd":"hello12"},{"message_recd":"hello again"},{"message_recd":"hey whtas up"},{"message_recd":"jhkwdfjdw"},{"message_recd":"is it working"},{"message_recd":"qw"},{"message_recd":"sdfsdfsdfsadf"},{"message_recd":"qwertyuiop"},{"message_recd":"aaaa"},{"message_sent":"hey whtas up"}] of type org.json.JSONArray cannot be converted to JSONObject
09-22 06:45:38.085: W/System.err(6513):     at org.json.JSON.typeMismatch(JSON.java:111)
09-22 06:45:38.085: W/System.err(6513):     at org.json.JSONObject.<init>(JSONObject.java:159)
09-22 06:45:38.085: W/System.err(6513):     at org.json.JSONObject.<init>(JSONObject.java:172)
09-22 06:45:38.085: W/System.err(6513):     at com.example.fetchdata.MainActivity.showList(MainActivity.java:55)
09-22 06:45:38.085: W/System.err(6513):     at com.example.fetchdata.MainActivityGetDataJSON.onPostExecute(MainActivity.java:130)
09-22 06:45:38.095: W/System.err(6513):     at com.example.fetchdata.MainActivityGetDataJSON.onPostExecute(MainActivity.java:1)
09-22 06:45:38.095: W/System.err(6513):     at android.os.AsyncTask.finish(AsyncTask.java:632)
09-22 06:45:38.095: W/System.err(6513):     at android.os.AsyncTask.access0(AsyncTask.java:177)
09-22 06:45:38.095: W/System.err(6513):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
09-22 06:45:38.095: W/System.err(6513):     at android.os.Handler.dispatchMessage(Handler.java:102)
09-22 06:45:38.095: W/System.err(6513):     at android.os.Looper.loop(Looper.java:136)
09-22 06:45:38.095: W/System.err(6513):     at android.app.ActivityThread.main(ActivityThread.java:5001)
09-22 06:45:38.095: W/System.err(6513):     at java.lang.reflect.Method.invokeNative(Native Method)
09-22 06:45:38.095: W/System.err(6513):     at java.lang.reflect.Method.invoke(Method.java:515)
09-22 06:45:38.095: W/System.err(6513):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
09-22 06:45:38.095: W/System.err(6513):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
09-22 06:45:38.145: W/System.err(6513):     at dalvik.system.NativeStart.main(Native Method)

Json 输出 java

[{"message_recd":"asdadasda"},{"message_recd":"hello"},{"message_recd":"how r u"},{"message_recd":"hello\n"},{"message_recd":"hello"},{"message_recd":"1"},{"message_recd":"qd"},{"message_recd":"1"},{"message_recd":"hello12"},{"message_recd":"hello again"},{"message_recd":"hey whtas up"},{"message_recd":"jhkwdfjdw"},{"message_recd":"is it working"},{"message_recd":"qw"},{"message_recd":"sdfsdfsdfsadf"},{"message_recd":"qwertyuiop"},{"message_recd":"aaaa"},{"message_sent":"hey whtas up"}]

Myphp 代码

<?php

define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','progress_card');

$con = mysqli_connect(HOST,USER,PASS,DB);

$sql1 = "select * from student_detail where parentusername='suyash1'";
$res1 = mysqli_query($con,$sql1);

$row1=mysqli_fetch_array($res1);

$cl=$row1['class']."-".$row1['section'];
$sql2="select * from teachers where classassign='$cl'";
$res2 = mysqli_query($con,$sql2);

$row2=mysqli_fetch_array($res2);

$to=$row2['email'];
$from=$row1['parentemail'];



$result = array();

$sql = "select * from messages where to_email='".$to."' and from_email='".$from."'";
$res = mysqli_query($con,$sql);

while($row = mysqli_fetch_array($res))
{
array_push($result,array('message_recd'=>$row['message']));
}

$sqlw = "select * from messages where from_email='".$to."' and to_email='".$from."'";
$resw = mysqli_query($con,$sqlw);

while($row5 = mysqli_fetch_array($resw))
{

array_push($result,array('message_sent'=>$row5['message']));
}

//array_push($result,array('message_sent'=>"dfdsghdfgddfgdsd"));
//array_push($result,array('message_sent'=>"sfdsflkufhskfhdskjfsfssadfadsffsafasfsfsadfafsaf"));

//array_push($result,array('message_recd'=>$row1['parentemail'],'message_sent'=>$row2['email']));

echo json_encode($result);

mysqli_close($con);

?>

您的输出是 json 数组而不是 json 对象。你应该做 -

JSONArray jsonArray = new JSONArray(myJSON);

现在遍历此 json 数组以获取值。

[]中的内容表示它是JSONArray,而{}中的内容表示它是JSONObject。 您的 Json 响应以 [ 开头,因此它是一个数组而不是 JSONObject,因此您必须更改

JSONObject jsonObj = new JSONObject(myJSON);

JSONArray  jArray=new JSONArray (myJSON);

现在可以遍历JSONArray了

for(int i=0;i<jArray.length();i++){
   JSONObject people =jArray.getJSONObject(i);
   // Now get all required values from people (JSONObject) 
}    

使用以下代码更改您的 showList() 函数:

 protected void showList(){
    try {
        JSONArray peoples = new JSONArray(myJSON);

        for(int i=0;i<peoples.length();i++){
            JSONObject c = peoples.getJSONObject(i);
            String name=null, address=null;
            if(c.has("message_recd"))
                name = c.getString("message_recd");
            else if(c.has("message_sent"))
                address = c.getString("message_sent");

            HashMap<String,String> persons = new HashMap<String,String>();
            persons.put(TAG_NAME,name);
            persons.put(TAG_ADD,address);
            personList.add(persons);
        }

        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, personList, R.layout.list_item,
                new String[]{TAG_NAME,TAG_ADD},
                new int[]{R.id.name, R.id.address}
        );

        list.setAdapter(adapter);

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

你的输出是 JSON 数组而不是对象,试试这个解决方案

更改以下代码

JSONObject jsonObj = new JSONObject(myJSON);
JSONArray  peoples = jsonObj.getJSONArray(TAG_RESULTS);

JSONArray peoples = new JSONArray(myJSON);