Search code examples
androidandroid-jsonandroid-databasejsonparser

Json parsing error: type org.json.JSONArray cannot be converted to JSONObject


The JSON is simple as,

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

The error I get is,

08-26 02:28:49.130 13605-13641/com.whatever.emshive E/MainActivity: Response from url: [{"kw":"48.90","kva":"51.20","pf":"-0.96"}] Json parsing error: Value [{"kw":"48.90","kva":"51.20","pf":"-0.96"}] of type org.json.JSONArray cannot be converted to JSONObject 08-26 02:28:49.130 13605-13641/com.whatever.emshive E/JSON Parser: Error parsing data org.json.JSONException: Value [{"kw":"48.90","kva":"51.20","pf":"-0.96"}] of type org.json.JSONArray cannot be converted to JSONObject

Code is,

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);
    }

}

}

I have tried looking at other similar answers in StackOverflow, couldn't get it. Help is much appreciated. Thank You


Solution

  • Please change the code in GetContacts.doInBackground from

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

    to

    JSONArray contacts = new JSONArray(jsonStr);