Как я могу пропустить нежелательные значения с помощью JsonReader?

Я пытался проанализировать файл JSON с помощью JsonReader. Я использую функцию skipvalue() для перехода к следующему ключу, но вместо перехода к следующему ключу синтаксический анализатор переходит к концу файла.

Файл выглядит так:

{
   "data":{
      "current_condition":[
         {
            "cloudcover":"100",
            "humidity":"74",
            "observation_time":"01:28 PM",
            "precipMM":"0.4",
            "pressure":"1005",
            "temp_C":"-3",
            "temp_F":"27",
            "visibility":"6",
            "weatherCode":"326",
            "weatherDesc":[
               {
                  "value":"Light snow"
               }
            ],
            "weatherIconUrl":[
               {
                  "value":"http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0011_light_snow_showers.png"
               }
            ],
            "winddir16Point":"NE",
            "winddirDegree":"50",
            "windspeedKmph":"15",
            "windspeedMiles":"9"
         }
      ],
      "request":[
         {
            "query":"Minsk, Belarus",
            "type":"City"
         }
      ],
      "weather":[
         {
            "date":"2013-03-20",
            "precipMM":"4.4",
            "tempMaxC":"-4",
            "tempMaxF":"25",
            "tempMinC":"-13",
            "tempMinF":"10",
            "weatherCode":"326",
            "weatherDesc":[
               {
                  "value":"Light snow"
               }
            ],
            "weatherIconUrl":[
               {
                  "value":"http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0011_light_snow_showers.png"
               }
            ],
            "winddir16Point":"NE",
            "winddirDegree":"40",
            "winddirection":"NE",
            "windspeedKmph":"17",
            "windspeedMiles":"11"
         },
         {
            "date":"2013-03-21",
            "precipMM":"0.6",
            "tempMaxC":"-5",
            "tempMaxF":"23",
            "tempMinC":"-15",
            "tempMinF":"5",
            "weatherCode":"326",
            "weatherDesc":[
               {
                  "value":"Light snow"
               }
            ],
            "weatherIconUrl":[
               {
                  "value":"http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0011_light_snow_showers.png"
               }
            ],
            "winddir16Point":"NE",
            "winddirDegree":"38",
            "winddirection":"NE",
            "windspeedKmph":"12",
            "windspeedMiles":"7"
         },
         {
            "date":"2013-03-22",
            "precipMM":"0.1",
            "tempMaxC":"-9",
            "tempMaxF":"17",
            "tempMinC":"-19",
            "tempMinF":"-2",
            "weatherCode":"119",
            "weatherDesc":[
               {
                  "value":"Cloudy"
               }
            ],
            "weatherIconUrl":[
               {
                  "value":"http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0003_white_cloud.png"
               }
            ],
            "winddir16Point":"NE",
            "winddirDegree":"51",
            "winddirection":"NE",
            "windspeedKmph":"19",
            "windspeedMiles":"12"
         },
         {
            "date":"2013-03-23",
            "precipMM":"0.0",
            "tempMaxC":"-8",
            "tempMaxF":"18",
            "tempMinC":"-13",
            "tempMinF":"8",
            "weatherCode":"116",
            "weatherDesc":[
               {
                  "value":"Partly Cloudy"
               }
            ],
            "weatherIconUrl":[
               {
                  "value":"http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png"
               }
            ],
            "winddir16Point":"NNE",
            "winddirDegree":"12",
            "winddirection":"NNE",
            "windspeedKmph":"16",
            "windspeedMiles":"10"
         }
      ]
   }
}

Это мой код:

String json_url = "http://free.worldweatheronline.com/feed/weather.ashx?q="+city+"&format=json&num_of_days="+Integer.toString(days)+"&key=0592d3cc1b151105131103";
JsonReader forecastJsonReader = new JsonReader(new InputStreamReader(getUrlData(json_url)));
forecastJsonReader.beginArray();
while (forecastJsonReader.hasNext()) {
    String name = forecastJsonReader.nextName();
    if (name.equals("date")) {
        Log.d("WEATHER",forecastJsonReader.nextString());
    } else if(name.equals("tempMaxC")) {
        Log.d("WEATHER",forecastJsonReader.nextString());
    } else { 
        forecastJsonReader.skipValue();
    }

}
forecastJsonReader.endObject();
forecastJsonReader.close();

person user2013423    schedule 20.03.2013    source источник


Ответы (1)


Я не думаю, что это правильный способ анализа json с помощью jsonreader, сначала ваш json начинается с объекта, а не с массива, это пример того, как вы анализируете свой json

основная функция

reader.beginObject();

        while (reader.hasNext()) {

            String name = reader.nextName();

            if (name.equals("data")) {
                readData(reader);
            } else {
                reader.skipValue(); // avoid some unhandle events
            }
        }

reader.endObject();
reader.close();

функция чтения данных

private void readData(JsonReader reader) throws IOException {
    reader.beginObject();
    while(reader.hasNext()) {
    String name = reader.nextName();
    if(name.equals("weather")) {
    reader.beginArray();
    while (reader.hasNext()) {
            reader.beginObject();
        String objectWeatherName = reader.nextName();
        if (objectWeatherName .equals("date")) {
             Log.d("WEATHER",reader.nextString());
        } else if (objectWeatherName .equals("tempMaxC")) {
             Log.d("WEATHER",reader.nextString());
        } else {
             reader.skipValue();
        }
            reader.endObject();
    }
    reader.endArray();
    } else {
        reader.skipValue();
    }

    }
    reader.endObject();
}

это если вы хотите прочитать дату и tempMaxC в объекте погоды, который находится в объекте данных, я надеюсь, вы понимаете мой ответ, но если у вас есть какие-либо вопросы, не стесняйтесь задавать их в комментарии :)

person Niko Adrianus Yuwono    schedule 20.03.2013
comment
Спасибо большое. Ваш код был очень полезен, но программа дала сбой на строке if(name.equals(weather)) {reader.beginObject();.И это другая проблема - person user2013423; 20.03.2013
comment
дело в том, что объект Weather содержит массив, поэтому в первый раз мы должны использовать reader.beginarray и reader.beginobject. Еще раз спасибо. Вы очень помогли - person user2013423; 20.03.2013
comment
как узнать сколько объектов в массиве? - person user2013423; 20.03.2013
comment
@user2013423 user2013423 извините, я пропустил скобку [теперь я отредактировал свой ответ, чтобы узнать, сколько объектов в массиве вы можете подсчитать, сколько циклов в while reader.hasnext после reader.beginArray() но вы это будете потреблять, что на самом деле вы хотите сделать с длиной массива? - person Niko Adrianus Yuwono; 21.03.2013