无法将JSONArray转换为JSONObject

时间:2012-03-10 05:01:35

标签: php mysql json parsing listview

那里。我是一名开始学习构建Android应用程序的学生......

我的代码在这里遇到了困难......

我读了很多页面如何解决问题,我还没有找到它......或者我可能不理解。 HAHAH

logcat总是这样:

03-10 11:12:43.057: D/dalvikvm(636): GC_EXTERNAL_ALLOC freed 1001 objects / 69352 bytes in 99ms
03-10 11:12:46.458: E/JSON Parser(636): Error parsing data org.json.JSONException: Names must be strings, but [{"pass_mobile":"affanganteng","user_mobile":"affan"},{"pass_mobile":"affandroid1","user_mobile":"affandroid"},{"pass_mobile":"tes","user_mobile":"tes"},{"pass_mobile":"tesdua","user_mobile":"tes2"}] is of type org.json.JSONArray at character 200 of {[{"user_mobile":"affan","pass_mobile":"affanganteng"},{"user_mobile":"affandroid","pass_mobile":"affandroid1"},{"user_mobile":"tes","pass_mobile":"tes"},{"user_mobile":"tes2","pass_mobile":"tesdua"}]}
03-10 11:35:00.868: D/dalvikvm(644): GC_EXTERNAL_ALLOC freed 1014 objects / 69872 bytes in 71ms
03-10 11:35:03.629: E/JSON Parser(644): Error parsing data org.json.JSONException: Value [{"pass_mobile":"affanganteng","user_mobile":"affan"},{"pass_mobile":"affandroid1","user_mobile":"affandroid"},{"pass_mobile":"tes","user_mobile":"tes"},{"pass_mobile":"tesdua","user_mobile":"tes2"}] of type org.json.JSONArray cannot be converted to JSONObject
03-10 11:40:58.798: D/dalvikvm(671): GC_EXTERNAL_ALLOC freed 744 objects / 59488 bytes in 80ms
03-10 11:41:03.128: E/JSON Parser(671): Error parsing data org.json.JSONException: Value [{"pass_mobile":"affanganteng","user_mobile":"affan"},{"pass_mobile":"affandroid1","user_mobile":"affandroid"},{"pass_mobile":"tes","user_mobile":"tes"},{"pass_mobile":"tesdua","user_mobile":"tes2"}] of type org.json.JSONArray cannot be converted to JSONObject

实际上我想从我的sql获取数据,然后使用JSON将其解析为listview。 我希望你能帮助我!

这是我的主要活动:

package last.project.CuliGUI;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AndroidJSONParsingActivity extends ListActivity {

    // url to make request
    private static String url = "http://10.0.2.2/culigui/getdatausermobile_2.php";

    // JSON Node names
    //private static final String TAG_LISTUSERMOBILE = "listusermobile";
    private static final String TAG_USER_MOBILE = "user_mobile";
    private static final String TAG_PASS_MOBILE = "pass_mobile";

    // contacts JSONArray
    JSONArray listusermobile = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu_view_all);

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> userList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Contacts
            //listusermobile = json.getJSONArray(TAG_LISTUSERMOBILE);
            listusermobile = json.getJSONArray(null);

            // looping through All Contacts
            for(int i = 0; i < listusermobile.length(); i++){
                JSONObject c = listusermobile.getJSONObject(i);

                // Storing each json item in variable
                String username = c.getString(TAG_USER_MOBILE);
                String password = c.getString(TAG_PASS_MOBILE);

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

                // adding each child node to HashMap key => value
                map.put(TAG_USER_MOBILE, username);
                map.put(TAG_PASS_MOBILE, password);
                // adding HashList to ArrayList
                userList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, userList,
                R.layout.menu_view_all,
                new String[] { TAG_USER_MOBILE, TAG_PASS_MOBILE}, new int[] {
                        R.id.name, R.id.pass });

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();

        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView)  view.findViewById(R.id.name)).getText().toString();
                String pass = ((TextView) view.findViewById(R.id.pass)).getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                in.putExtra(TAG_USER_MOBILE, name);
                in.putExtra(TAG_PASS_MOBILE, pass);
                startActivity(in);

            }
        });



    }

}

这里是我的JSONParser类:

package last.project.CuliGUI;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

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);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } 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);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

这是php:

<?php

    $link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB');
    mysql_select_db('culigui', $link) or die('Cannot select the DB');



    $result = sql2json("SELECT * FROM data_mobile");

    echo $result;

    //Function will take an SQL query as an argument and format the resulting data as a 
//    json(JavaScript Object Notation) string and return it.
function sql2json($query) {
    $data_sql = mysql_query($query) or die("'';//" . mysql_error());// If an error has occurred, 
            //    make the error a js comment so that a javascript error will NOT be invoked
    $json_str = ""; //Init the JSON string.

    if($total = mysql_num_rows($data_sql)) { //See if there is anything in the query
        $json_str .= "[\n";

        $row_count = 0;    
        while($data = mysql_fetch_assoc($data_sql)) {
            if(count($data) > 1) $json_str .= "{\n";

            $count = 0;
            foreach($data as $key => $value) {
                //If it is an associative array we want it in the format of "key":"value"
                if(count($data) > 1) $json_str .= "\"$key\":\"$value\"";
                else $json_str .= "\"$value\"";

                //Make sure that the last item don't have a ',' (comma)
                $count++;
                if($count < count($data)) $json_str .= ",\n";
            }
            $row_count++;
            if(count($data) > 1) $json_str .= "}\n";

            //Make sure that the last item don't have a ',' (comma)
            if($row_count < $total) $json_str .= ",\n";
        }

        $json_str .= "]\n";
    }

    //Replace the '\n's - make it faster - but at the price of bad redability.
    $json_str = str_replace("\n","",$json_str); //Comment this out when you are debugging the script

    //Finally, output the data
    return $json_str;
}


?>

1 个答案:

答案 0 :(得分:0)

首先,以下是 NOT 有效的JSON对象:

{
    [
        {
            "user_mobile": "affan",
            "pass_mobile": "affanganteng"
        },
        {
            "user_mobile": "affandroid",
            "pass_mobile": "affandroid1"
        },
        {
            "user_mobile": "tes",
            "pass_mobile": "tes"
        },
        {
            "user_mobile": "tes2",
            "pass_mobile": "tesdua"
        }
    ]
}

在您的JAVA代码中,您正在迭代JSON对象,并获取Sub JSON对象..

JSONObject c = listusermobile.getJSONObject(i);

但是在JSON对象中,你持有JSON Array ( [] ),而不是JSON Object ( {} ) ..但是你正在尝试 TypeCast JSON Array进入JSON Object.这就是造成错误的原因......

注意:您始终可以在JSONLint.com验证“VALID JSONObject”和“VALID JSONArray”