не удалось получить данные из jsonobject

#android

#Android

Вопрос:

ответ json

 {
  "Qa": {
    "qa_id": "146",
    "qa_title": "title",
    "qa_description": "Des",
    "user_id": "23",
    "is_answer": "N",
    "is_publish": "N",
    "post_date": "2016-10-16 00:00:00",
    "created": "2016-10-17 17:59:02",
    "modified": "2016-10-17 17:59:02"
  },
  "User": {
    "user_id": "23",
    "full_name": "Malyagiri (Junior) Mahavidyalaya, Pallahara",
    "username": "YC20",
    "password": "5f4dcc3b5aa765d61d8327deb882cf99",
    "m_user_type_id": "2",
    "m_desg_id": "2",
    "m_state_id": "1",
    "m_district_id": "1",
    "m_block_id": "9",
    "m_organization_id": "20",
    "mobile_no": null,
    "email_id": null,
    "contact_no": null,
    "is_active": "Y",
    "api_key": "0bd4f8c8a394c8ca2a21cd945d0fae54",
    "created": null,
    "modified": null,
    "device_id": null,
    "MUserType": {
      "m_user_type_id": "2",
      "m_user_type": "Nodal Officer"
    },
    "MDesg": {
      "m_desg_id": "2",
      "m_desg_nm": "Nodal Officer"
    },
  

и фоновый класс

  @Override
        protected Void doInBackground(String... params) {


            try {
                String last_id = params[0];
                InputStream in = null;
                int resCode = -1;
                String link = Constants.LOCAL_ADD_USER   Constants.QUESTION_LIST;
                URL url = new URL(link);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setAllowUserInteraction(false);
                conn.setInstanceFollowRedirects(true);
                conn.setRequestMethod("POST");

                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("last_id ", last_id);

                String query = builder.build().getEncodedQuery();

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();

                conn.connect();
                resCode = conn.getResponseCode();
                if (resCode == HttpURLConnection.HTTP_OK) {
                    in = conn.getInputStream();
                }
                if (in == null) {
                    return null;
                }
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                String response = "", data = "";

                while ((data = reader.readLine()) != null) {
                    response  = data   "n";
                }

                Log.i(TAG, "Response : "   response);



                if (response != null amp;amp; response.length() > 0) {

                    JSONObject res = new JSONObject(response);
                    JSONArray json2 = res.getJSONArray("Qa");
                  ///  JSONArray district = res.getJSONArray("Qa");



                   /* for (int i = 0; i < json2.length(); i  ) {

                        JSONObject distObj = json2.getJSONObject(i);


                        int m_distid = distObj.getInt("m_district_id");
                        String m_distlist = distObj.getString("m_district");


                    }*/

                }


                return null;


            } catch (Exception exception) {
                Log.e(TAG, "LoginAsync : doInBackground", exception);
            }
            return null;
        }
  

Ответ №1:

Данный JSONbject находится в неправильном формате. например, в данном JSONObject отсутствуют две закрывающие фигурные скобки }}

пожалуйста, проверьте форматирование с помощью jsonformatter. Ссылка приведена ниже

(https://jsonformatter.curiousconcept.com /)

Ответ №2:

 JSONObject res = new JSONObject(response);
JSONObject json2 = res.getJSONObject("Qa");
  

Ответ №3:

В вашем JSON отсутствуют две фигурные скобки в конце, чтобы быть действительными (вы можете использовать https://jsonformatter.curiousconcept.com / для его проверки), и запись for "Qa" не является JSONArray, это JSONObject . Итак, вам нужно изменить строку:

 JSONArray json2 = res.getJSONArray("Qa");
  

Для

 JSONObject json2 = res.getJSONObject("Qa");