简体   繁体   English

无法将类型为org.json.JSONObject $ 1的值null转换为JSONObject错误

[英]Value null of type org.json.JSONObject$1 cannot be converted to JSONObject error found

I want to show the userlist from JSON object url with POST method but its show me the error some thing like this :- Value null of type org.json.JSONObject$1 cannot be converted to JSONObject . 我想使用POST方法显示JSON对象url中的用户列表,但它向我显示了类似以下错误: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject and show the blank data in the activity. 并在活动中显示空白数据。 In this api link its shows :- 在此api链接中,其显示为:-

    {
    "data": [{
        "id": "38",
        "username": "atif"
    }, {
        "id": "37",
        "username": "ajay1"
    }, {
        "id": "36",
        "username": "akki"
    }, {
        "id": "35",
        "username": "a"
    }, {
        "id": "34",
        "username": "abc"
    }, {
        "id": "33",
        "username": "ankit"
    }, {
        "id": "32",
        "username": "riya"
    }, {
        "id": "31",
        "username": "akshay"
    }, {
        "id": "5",
        "username": "chitran"
    }, {
        "id": "4",
        "username": "kunal"
    }, {
        "id": "3",
        "username": "anshul"
    }, {
        "id": "2",
        "username": "XYZ"
    }, {
        "id": "1",
        "username": "XYZ"
    }],
    "resp_msg": "Success",
    "resp_code": 200
 }

Here is my code for showing the list from the json parsing. 这是我的代码,用于显示json解析中的列表。

parsing data 解析数据

http://codexpertise.com/codexpertise.com/apitest/service.php

{
    "type":"online_user"

}

Userlist.java Userlist.java

public class Userlist extends AppCompatActivity {

    private String TAG = Userlist.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;

    // URL to get contacts JSON
    private static String url = "http://codexpertise.com/codexpertise.com/apitest/service.php";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userlist);

        contactList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.listView1);

        new GetContacts().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(Userlist.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("data");

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

                        String id = c.getString("id");
                        String name = c.getString("username");




                        // tmp hash map for single contact
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("id", id);
                        contact.put("name", name);


                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    Userlist.this, contactList,
                    R.layout.list_items, new String[]{"id", "username"}, new int[]{R.id.name,
                    R.id.email});

            lv.setAdapter(adapter);
        }

    }
}

HttpHandler.java HttpHandler.java

public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

list_items.xml list_items.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="@dimen/activity_horizontal_margin">

    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textColor="@color/colorAccent" />

</LinearLayout>

activity_userlist.xml activity_userlist.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Userlist" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" >
    </ListView>

</RelativeLayout>

According to your JSON check below try block 根据您的JSON检查以下try block

try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("data");

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

                        String id = c.getString("id");
                        String name = c.getString("username");//change here


                        // Phone node is JSON Object
                       // JSONObject phone = c.getJSONObject("phone"); //this object not in JSON so remove it..
                        //String mobile = phone.getString("mobile");
                       // String home = phone.getString("home");
                       // String office = phone.getString("office");

                        // tmp hash map for single contact
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("id", id);
                        contact.put("name", name);


                        // adding contact to contact list
                        contactList.add(contact);
                    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 值类型 org.json.JSONObject 无法转换为 JSONArray - Value type org.json.JSONObject cannot be converted to JSONArray 无法将org.json.JSONObject类型的数据转换为JSONArray - Data of type org.json.JSONObject cannot be converted to JSONArray 类型为org.json.JSONObject的响应无法转换为JSONArray - at response of type org.json.JSONObject cannot be converted to JSONArray at 类型 org.json.JSONObject 的数据无法转换为 JSONArray - at data of type org.json.JSONObject cannot be converted to JSONArray org.json.JSONObject无法转换为JSONArray - org.json.JSONObject cannot be converted to JSONArray 错误org.json.JSONObject无法转换为JSONArray - error org.json.JSONObject cannot be converted to JSONArray 我有一个错误:类型 org.json.JSONObject 无法转换为 JSONArray - I have an error : type org.json.JSONObject cannot be converted to JSONArray 未找到类型为org.json.JSONObject的返回值的转换器 - No converter found for return value of type: class org.json.JSONObject org.json.JSONException:值 {“storeid0”:[“1535”],“storeid1”:[“1862”]} 类型为 org.json.JSONObject 的 idddsss 无法转换为 JSONArray - org.json.JSONException: Value {“storeid0”:[“1535”],“storeid1”:[“1862”]} at idddsss of type org.json.JSONObject cannot be converted to JSONArray 如何使用ResponseEntity返回JSONObject而不是HashMap? (未找到类型为org.json.JSONObject的返回值的转换器) - How to return a JSONObject instead HashMap with ResponseEntity? (No converter found for return value of type: class org.json.JSONObject)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM