Не удается преобразовать JSONArray в JSONObject - PullRequest
0 голосов
/ 10 марта 2012

есть. Я студент, который начинает изучать создание приложения для Android ...

У меня возникли проблемы с моим кодом здесь ...

Я прочитал много страниц, как решить проблему, и я не нашел ее ... или, может быть, я не понимаю. Хаха

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. Я надеюсь, что вы можете помочь мне!

вот моя основная деятельность:

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 голосов
/ 10 марта 2012

Прежде всего, следующее НЕ допустимый объект 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 JSONObject ..

JSONObject c = listusermobile.getJSONObject(i);

Но внутри объекта JSON вы держите JSON Array ( [] ), а не JSON Object ( {} ) .. Но вы пытаетесь TypeCast JSON Array в JSON Object.. именно это и вызывает ошибку ...

Примечание. Вы всегда можете проверить "VALID JSONObject" и "VALID JSONArray" на JSONLint.com

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...