Ошибка разбора Json: тип org.json.JSONArray не может быть преобразован в JSONObject - PullRequest
0 голосов
/ 26 августа 2018

JSON прост:

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

Я получаю ошибку:

08-26 02: 28: 49.130 13605-13641 / com.whwhat.emshive E / MainActivity: ответ от URL: [{"kw": "48.90", "kva": "51.20", "pf": "- 0.96"}] Ошибка анализа Json: значение [{"kw": "48.90", "kva": "51.20", "pf":"-0.96"}] типа org.json.JSONArray невозможно преобразовать в JSONObject 08-26 02: 28: 49.130 13605-13641 / com.whwhat.emshive Анализатор E / JSON: Ошибка при анализе данных org.json.JSONException: Value[{"kw": "48.90", "kva": "51.20", "pf": "- 0.96"}] типа org.json.JSONArray невозможно преобразовать в JSONObject

Код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);
    }

}

}

Я пытался посмотреть другие подобные ответы в StackOverflow, не смог получить его.Помощь очень ценится.Спасибо

Ответы [ 2 ]

0 голосов
/ 26 августа 2018

Пожалуйста, измените код в GetContacts.doInBackground с

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

на

JSONArray contacts = new JSONArray(jsonStr);
0 голосов
/ 26 августа 2018

Как говорится в сообщении, вы пытаетесь преобразовать массив JSON в объект JSON.Ваш JSON - это массив ...

...