mohamed salem
mohamed salem

Reputation: 77

JSON File / Android - Get the value of string

I have the following JSON file format :

{"code":200,
 "status":"OK",
 "data":[
   {"timings":
     {"Fajr":"03:11 (EET)",
      "Sunrise":"04:54 (EET)",
      "Dhuhr":"11:53 (EET)",
      "Asr":"15:29 (EET)",
      "Sunset":"18:52 (EET)",
      "Maghrib":"18:52 (EET)",
      "Isha":"20:23 (EET)",
      "Imsak":"03:01 (EET)",
      "Midnight":"23:53 (EET)"},....

I want to get the value of Asr (for example) & parse it into string variable, I tried the below but nothing works (Please note: response is successfully retrieved, so no issue with reaching the JSON file, but only to get the value of string).

String mfajr = response1.getJSONArray("data").getJSONObject(0)
                        .get("Fajr").toString();

String  mdoher = response1.getJSONArray("data").getJSONObject(0)
                          .getJSONArray("timings")
                          .get(Integer.parseInt("Dhuhr")).toString();

Upvotes: 0

Views: 103

Answers (1)

Stephen C
Stephen C

Reputation: 719551

Assuming that response1 is a JSONObject.

String mfajr = response1.getJSONArray("data")
                        .getJSONObject(0)
                        .get("Fajr").toString();

That will fail because getJSONObject(0) returns an object that has a "timings" attribute ... not a "Fajr" attribute.

String  mdoher = response1.getJSONArray("data")
                          .getJSONObject(0).getJSONArray("timings")
                          .get(Integer.parseInt("Dhuhr")).toString();

That will fail because the value of "timings" attribute is JSON object, not a JSON array.

Also, the value of the "Dhuhr" attribute is not an integer, so parseInt is not going to work. If you want the value as an integer, you are going to do some string analysis to convert "11:53 (EET)" to an integer.

Basically, you need to make sure that your Java code precisely matches the JSON structure. Close enough is NOT good enough.


OK .... so you want someone to write your code for you.

Try this:

String mfajr = response1.getJSONArray("data")
                        .getJSONObject(0)
                        .getJSONObject("timings")
                        .getString("Fajr");

Now, compare it with the structure of the JSON.

Upvotes: 1

Related Questions