2

Имеется такой JSON ответ

{
  response: {
    count: 19,
    items: [
      {
        id: 158,
        title: 'Челябинск',
        important: 1
      },
      {
        id: 88,
        title: 'Набережные Челны',
        important: 1
      },
      {
        id: 1,
        title: 'Москва',
        important: 1
      },
      {
        id: 2,
        title: 'Санкт-Петербург',
        important: 1
      }
    ]
  }
}

Пытаюсь распарсить вот так,

try {
  JSONObject object = new JSONObject(response.responseString);
  JSONArray array = object.getJSONArray("items");
  for (int i = 0; i < array.length(); i++) {
    JSONObject item = array.getJSONObject(i);
    City city = new City();
    String title = item.getString("title");
    int id = item.getInt("id");
    city.setTitle(title);
    city.setId(id);
    Log.d("VkParseLog", city.getTitle());
  }
} catch (JSONException e) {
  e.printStackTrace();
}

Но получаю вот это:

org.json.JSONException: No value for items
    at org.json.JSONObject.get(JSONObject.java:389)
    at org.json.JSONObject.getJSONArray(JSONObject.java:584)
    at ru.bullfinchdev.vkgram.SearchParamActivity$CitiesGet$1.onComplete(SearchParamActivity.java:92)
    at com.vk.sdk.api.VKRequest$3.run(VKRequest.java:482)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

2 ответа 2

6

Массив "items" находится внутри объекта "response", а вы пытаетесь получить его у корневого объекта.

try {
  JSONObject object = new JSONObject(response.responseString);
  JSONObject responseObject = object.getJSONObject("response");
  JSONArray array = responseObject.getJSONArray("items");
  for (int i = 0; i < array.length(); i++) {
    JSONObject item = array.getJSONObject(i);
    City city = new City();
    String title = item.getString("title");
    int id = item.getInt("id");
    city.setTitle(title);
    city.setId(id);
    Log.d("VkParseLog", city.getTitle());
  }
} catch (JSONException e) {
  e.printStackTrace();
}
-2
JSONArray array = object.getJSONArray("items");

на

JSONArray array = new JSONArray("items");

замените

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.