JSON解析错误:类型org.json.JSONArray无法转换为JSONObject

时间:2018-08-25 21:11:25

标签: android android-json android-database jsonparser

JSON很简单

  

[{“ kw”:“ 48.90”,“ kva”:“ 51.20”,“ pf”:“-0.96”}]

我得到的错误是

  

08-26 02:28:49.130 13605-13641 / com.whatever.emshive E / MainActivity:   网址的响应:[{“ kw”:“ 48.90”,“ kva”:“ 51.20”,“ pf”:“-0.96”}]       Json解析错误:类型为org.json.JSONArray的值[{“ kw”:“ 48.90”,“ kva”:“ 51.20”,“ pf”:“-0.96”}]   无法转换为JSONObject 08-26 02:28:49.130   13605-13641 / com.whatever.emshive E / JSON解析器:解析数据时出错   org.json.JSONException:值   org.json.JSONArray类型的[{“ kw”:“ 48.90”,“ kva”:“ 51.20”,“ pf”:“-0.96”}]   无法转换为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://simpleasthat.com/s.php";

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(0);

                    String kw = c.getString("kw");
                    String kva = c.getString("kva");
                    String pf = c.getString("pf");

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

                    // adding each child node to HashMap key => value
                    contact.put("kw", kw);
                    contact.put("kva", kva);
                    contact.put("pf", pf);

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                Log.e("JSON Parser", "Error parsing data " + e.toString());
                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[]{"kw", "kva",
                "pf"}, new int[]{R.id.kw,
                R.id.kva, R.id.pf});

        lv.setAdapter(adapter);
    }

}

}

我尝试在StackOverflow中查看其他类似的答案,但无法理解。非常感谢您的帮助。谢谢

2 个答案:

答案 0 :(得分:1)

如消息所示,您正在尝试将JSON数组转换为JSON对象。您的JSON是一个数组...

答案 1 :(得分:1)

请从以下位置更改GetContacts.doInBackground中的代码

JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");

JSONArray contacts = new JSONArray(jsonStr);