【问题标题】:Android : java.lang.String cannot be converted to JSONObjectAndroid:java.lang.String 无法转换为 JSONObject
【发布时间】:2017-07-16 11:14:45
【问题描述】:

我收到错误:

java.lang.String 无法转换为 JSONObject

我想在这个网站(http://www.androidhive.info/2012/01/android-json-parsing-tutorial/)上测试这个教程,但是我有一个错误(java.lang.String 类型的值不能被转换为 JSONObject),谢谢你的帮助

public class MainActivity extends AppCompatActivity {

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

private ProgressDialog pDialog;
private ListView lv;

// URL to get contacts JSON
private static String url = "http://api.androidhive.info/contacts/";

ArrayList<HashMap<String, String>> contactList;

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

    contactList = new ArrayList<>();

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

    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(MainActivity.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("contacts");

                // 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("name");
                    String email = c.getString("email");
                    String address = c.getString("address");
                    String gender = c.getString("gender");

                    // Phone node is JSON Object
                    JSONObject phone = c.getJSONObject("phone");
                    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);
                    contact.put("email", email);
                    contact.put("mobile", mobile);

                    // 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(
                MainActivity.this, contactList,
                R.layout.list_item, new String[]{"name", "email",
                "mobile"}, new int[]{R.id.name,
                R.id.email, R.id.mobile});

        lv.setAdapter(adapter);
    }

 }
}

【问题讨论】:

  • 在同一网站上查看 Ravi Tamada 的最新教程,了解使用 Volley 进行 JSON 解析,让您的生活更轻松。
  • 您遇到了什么异常?发布您的日志猫
  • 如果您可以包含足以重现问题的内容,那将会很有帮助。见:How to create a Minimal, Complete, and Verifiable example

标签: java android json parsing


【解决方案1】:

将网址更改为“https://api.androidhive.info/contacts/”;

https而不是http它会起作用

我自己下载了代码并检查了它。实际上,即使没有互联网连接,该错误也会随时出现。这个演示非常基础,并没有很好地处理异常。因此,从技术上讲,当请求失败时, sh.makeServiceCall(url); 会返回一个空白字符串; Android 无法转换成 JSON。

所以只要确保设备上的互联网连接正常,否则修改 sh.makeServiceCall(url) 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2012-12-12
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多