通过PHP文件获取JSON时,JSONArray无法转换为JSONObject错误

时间:2015-03-30 09:44:52

标签: php android json parsing

我知道这里存在同样的问题,但我相信我的情况不同,我觉得这令人困惑。当我的JSON链接为private static String url = "http://10.0.2.2/shareity/test.php/";时,我收到了该错误。但是当我在文本文件private static String url = "http://10.0.2.2/shareity/json.txt";中拥有完全相同的JSON数据时,它可以完美地运行。我的问题是,当我仅从PHP文件本身获取JSON时,为什么会发生这种情况?

我的logcat:

03-30 09:31:01.250: E/JSON Parser(3129): Error parsing data     org.json.JSONException: Value [{"eid":"1","ename":"First","edesc":"Chirath"},    {"eid":"2","ename":"New one","edesc":"Checking if tiisssf"},    {"eid":"3","ename":"Blood Donation","edesc":"Giv the blud"},    {"eid":"4","ename":"Clean","edesc":"cleant eh thin g"}] of type org.json.JSONArray cannot be converted to JSONObject
03-30 09:31:01.260: W/EGL_emulation(3129): eglSurfaceAttrib not implemented
03-30 09:31:01.260: W/OpenGLRenderer(3129): Failed to set EGL_SWAP_BEHAVIOR     on surface 0x7ff0079d5140, error=EGL_SUCCESS
03-30 09:31:01.310: D/AndroidRuntime(3129): Shutting down VM
03-30 09:31:01.310: E/AndroidRuntime(3129): FATAL EXCEPTION: main
03-30 09:31:01.310: E/AndroidRuntime(3129): Process: learn2crack.listview,     PID: 3129
03-30 09:31:01.310: E/AndroidRuntime(3129): java.lang.NullPointerException:     Attempt to invoke virtual method 'org.json.JSONArray     org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
03-30 09:31:01.310: E/AndroidRuntime(3129):     at     learn2crack.listview.MainActivity$JSONParse.onPostExecute(MainActivity.java:108)
03-30 09:31:01.310: E/AndroidRuntime(3129):     at     learn2crack.listview.MainActivity$JSONParse.onPostExecute(MainActivity.java:1)
03-30 09:31:01.310: E/AndroidRuntime(3129):     at     android.os.AsyncTask.finish(AsyncTask.java:632)
03-30 09:31:01.310: E/AndroidRuntime(3129):     at     android.os.AsyncTask.access$600(AsyncTask.java:177)
03-30 09:31:01.310: E/AndroidRuntime(3129):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
03-30 09:31:01.310: E/AndroidRuntime(3129):     at     android.os.Handler.dispatchMessage(Handler.java:102)
03-30 09:31:01.310: E/AndroidRuntime(3129):     at     android.os.Looper.loop(Looper.java:135)
03-30 09:31:01.310: E/AndroidRuntime(3129):     at     android.app.ActivityThread.main(ActivityThread.java:5221)
03-30 09:31:01.310: E/AndroidRuntime(3129):     at     java.lang.reflect.Method.invoke(Native Method)
03-30 09:31:01.310: E/AndroidRuntime(3129):     at     java.lang.reflect.Method.invoke(Method.java:372)
03-30 09:31:01.310: E/AndroidRuntime(3129):     at     com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
03-30 09:31:01.310: E/AndroidRuntime(3129):     at     com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

这是我的主要活动

public class MainActivity extends Activity {
ListView list;
TextView eid;
TextView ename;
TextView edesc;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();

//URL to get JSON Array
private static String url = "http://10.0.2.2/shareity/test.php/";

//JSON Node Names 
private static final String TAG_OS = "events";
private static final String TAG_EID = "eid";
private static final String TAG_ENAME = "ename";
private static final String TAG_EDESC = "edesc";

JSONArray events = null;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    oslist = new ArrayList<HashMap<String, String>>();



    Btngetdata = (Button)findViewById(R.id.getdata);
    Btngetdata.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
             new JSONParse().execute();


        }
    });


}



private class JSONParse extends AsyncTask<String, String, JSONObject> {
     private ProgressDialog pDialog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
         eid = (TextView)findViewById(R.id.vers);
         ename = (TextView)findViewById(R.id.name);
         edesc = (TextView)findViewById(R.id.api);
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Getting Data ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();



    }

    @Override
    protected JSONObject doInBackground(String... args) {

        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        return json;
    }
     @Override
     protected void onPostExecute(JSONObject json) {
         pDialog.dismiss();
         try {
                // Getting JSON Array from URL
                events = json.getJSONArray(TAG_OS);
                for(int i = 0; i < events.length(); i++){
                JSONObject c = events.getJSONObject(i);

                // Storing  JSON item in a Variable
                String eid = c.getString(TAG_EID);
                String ename = c.getString(TAG_ENAME);
                String edesc = c.getString(TAG_EDESC);




                // Adding value HashMap key => value


                HashMap<String, String> map = new HashMap<String, String>();

                map.put(TAG_EID, eid);
                map.put(TAG_ENAME, ename);
                map.put(TAG_EDESC, edesc);

                oslist.add(map);
                list=(ListView)findViewById(R.id.list);





                ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
                        R.layout.list_v,
                        new String[] { TAG_EID,TAG_ENAME, TAG_EDESC }, new int[] {
                                R.id.vers,R.id.name, R.id.api});

                list.setAdapter(adapter);
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();

                    }
                });

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


     }
}

}

这是我的php API:

<?php

//Create Database connection

$db = mysql_connect("localhost","root","");

if (!$db) {

    die('Could not connect to db: ' . mysql_error());

}


//Select the Database

mysql_select_db("shareity",$db);



//Replace * in the query with the column names.

$result = mysql_query("select * from event2", $db); 



//Create an array

$json_response = array();



while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

    $row_array['eid'] = $row['eid'];

    $row_array['ename'] = $row['ename'];

    $row_array['edesc'] = $row['edesc'];

    //$row_array['esdate'] = $row['esdate'];

    //$row_array['eedate'] = $row['eedate'];

    //$row_array['estime'] = $row['estime'];

    //$row_array['eetime'] = $row['eetime'];

    //$row_array['egoal'] = $row['egoal'];

    //$row_array['createdby'] = $row['createdby'];




    //push the values in the array

    array_push($json_response,$row_array);

}

echo json_encode($json_response);



//Close the database connection

fclose($db);



?>

这是我的JSONParser类:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        //BufferedReader reader = new BufferedReader(new InputStreamReader(
                //is, "iso-8859-1"), 8);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        Log.d("JSON before to string: ", "> " + json);
        json = sb.toString();
        Log.d("JSON after to string: ", "> " + json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
        Log.d("JSONObject: ", "> " + jObj);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

2 个答案:

答案 0 :(得分:0)

试试这个,它会起作用 将以下内容放在php代码的顶部

header('Content-Type: application/json');

并首先关闭mysql连接而不是fclose(我不确定)

mysql_close();

echo json_encode(array('events'=>$json_response));

答案 1 :(得分:0)

你从字符串创建jsonObject,但是这个字符串是jsonarray

JSONArray jsonArray = new JSONArray(yourJSONString);
for(int i = 0; i < jsonArray.length(); i++) {
    JSONObject jsonObj = jsonArray.getJSONObject(i);
}