Slobodan Vrhovac
Slobodan Vrhovac

Reputation: 25

JSON Array not returning data

I have this JSON data and Im having problem to extract data for my weather app. Im getting JSONexception and I dont know why

{
  "city": {
    "id": 792680,
    "name": "Belgrade",
    "coord": {
      "lon": 20.46513,
      "lat": 44.804008
    },
    "country": "RS",
    "population": 0,
    "sys": {
      "population": 0
    }
  },
  "cod": "200",
  "message": 0.0106,
  "cnt": 9,
  "list": [
    {
      "dt": 1437944400,
      "main": {
        "temp": 17.99,
        "temp_min": 17.99,
        "temp_max": 20.44,
        "pressure": 1013.8,
        "sea_level": 1024.97,
        "grnd_level": 1013.8,
        "humidity": 60,
        "temp_kf": -2.45
      },
      "weather": [
        {
          "id": 800,
          "main": "Clear",
          "description": "sky is clear",
          "icon": "01n"
        }
      ],
      "clouds": {
        "all": 0
      },
      "wind": {
        "speed": 2.41,
        "deg": 347
      },
      "rain": {
        
      },
      "sys": {
        "pod": "n"
      },
      "dt_txt": "2015-07-26 21:00:00"
    },

My method for extraction look like this.

private void renderWeather(JSONObject json) {
    try {

        String precipitation = "N/A";

        JSONArray listObjects = json.getJSONArray("list");
        for (int i = 0; i < listObjects.length(); i++) {
            JSONObject JSONobj1 = listObjects.getJSONObject(i);

            DateFormat df = DateFormat.getDateTimeInstance();
            String time = df.format(new Date(json.getLong("dt") * 1000));

            if (JSONobj1.getJSONObject("rain").length() != 0) {
                precipitation = JSONobj1.getJSONObject("rain").getString("3h");
            }

            String temperature = JSONobj1.getJSONObject("main").getString("temp");

            int weatherIconId = JSONobj1.getJSONArray("weather").getJSONObject(0).getInt("id");

            HourlyForecast hourlyForecast = new HourlyForecast(time, precipitation, temperature, weatherIconId);
            hourlyForecastArrayList.add(hourlyForecast);


        }
    } catch (Exception e) {
        Log.e("SimpleWeather", "One or more fields not found in the JSON data");
        Toast.makeText(getActivity(), "No JSON data found", Toast.LENGTH_LONG).show();
    }
}

Here is the exception.

 org.json.JSONException: No value for dt
        at org.json.JSONObject.get(JSONObject.java:354)
        at org.json.JSONObject.getLong(JSONObject.java:477)
        at com.slobx.slobodan.weathermob.Tab3.renderWeather(Tab3.java:107)
        at com.slobx.slobodan.weathermob.Tab3.access$000(Tab3.java:31)
        at com.slobx.slobodan.weathermob.Tab3$1$2.run(Tab3.java:89)
        at android.os.Handler.handleCallback(Handler.java:615)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4745)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

at this line

String time = df.format(new Date(json.getLong("dt") * 1000));

Thanks for your help.

Upvotes: 0

Views: 319

Answers (3)

bcorso
bcorso

Reputation: 47078

I would suggest using the Gson library. Gson makes this kind of stuff really easy.

All you need to do is define POJOs for each Json object in your json file. You don't need to write any code to convert to JsonObject/JsonArray, Gson handles that for you.

The POJO classes should be defined with the same names as the json keys, and with appropriate datatypes (your json structure could probably use some refactoring).

class CityInfo {
    City city;
    String cod;
    double message;
    int cnt;
    List<Info> list;
}

class City {
    int id, population;
    String name, country;
    Coord coord;
    Sys sys;
}

class Coord {
    double lon, lat;
}

class Sys {
    int population;
}

class Info {
    long dt;
    String dt_text;
    Main main;
    Weather weather;
    Clouds clouds;
    Wind wind;
    Rain rain;
    Sys2 sys;
}

class Main {
    double temp, tempMin, tempMax, pressure, seaLevel, grndLevel, humidity, tempKf;
}

class Weather {
    int id;
    String main, description, icon;
}

class Clouds {
   int all;
}

class Wind {
    double speed;
    int deg;
}

class Rain{}

class Sys2 {
    String pod;
}

Once you've defined the POJOs properly, you can convert between json-string <-> POJO like this:

// Build a gson object responsible for conversion and set naming convention
Gson gson = new GsonBuilder()
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    .create()

// Convert from json-string to POJO
BufferedReader br = new BufferedReader(new FileReader("file.json"));
CityInfo cityInfo = gson.fromJson(br, CityInfo.class);

// Convert from POJO to json-string
String json = gson.toJson(cityInfo);

Upvotes: 0

uknowbigmams
uknowbigmams

Reputation: 71

This is because you use json.getString(" dt") instead of JSONobj1.getString("dt")

Upvotes: 1

yugidroid
yugidroid

Reputation: 6690

Probably some positions of list array might not have dt property defined.

Before using the values make sure if they exist using json.isNull("dt") or use optString(), etc. These methods won't throw any exception but will return null or 0 instead.

Upvotes: 0

Related Questions