Trusted
Trusted

Reputation: 235

Retrieve data from JSON Java Android

i've got a problem to retrieve information by a JSON

The Raw Json is this

{"date":"{\"yesterday\":\"Wed 28\",\"today\":\"Thu 29\",\"tomorrow\":\"Fri 30\"}"

Now how i could take this Json and format in this?

{
    "date":{
        "yesterday":"Wed 28",
        "today":"Thu 29",
        "tomorrow":"Fri 30"
    }
}

And then retry the date from the key?

            String jsonStr = sh.makeServiceCall(url); 
            Log.e("RAW-JSON: ","Retrieve RAW-Json is "+jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    JSONArray DATESTRING = jsonObj.getJSONArray("date");
                    JSONObject d = DATESTRING.getJSONObject(0);
                    String Ieri = d.getString("yesterday");
                    Log.e("DATE-JSON", "Retrieve DATE-Json is " + yesterday);
                } catch (JSONException e) {
                    Log.e("ERROR", "Not a good result.");
                    e.printStackTrace();
                }
            }

Upvotes: 0

Views: 53

Answers (4)

Arnav Rao
Arnav Rao

Reputation: 7002

Just simply replace \" with " to get clean json string and then parse the json to read data usig JSONObjct.

jsonStr = jsonStr.replace("\\\"", "\"");
JSONObject jsonObj = new JSONObject(jsonStr);

Upvotes: 0

catchiecop
catchiecop

Reputation: 388

What you probably need to do is (assuming you want today's date):

String todaysDate = jsonObj.getJSONObject("date").getString("today");

Upvotes: 0

Andrea Radice
Andrea Radice

Reputation: 1

JSONArray DATESTRING = jsonObj.getJSONArray("date") is wrong because "date" is not an JsonArray but an JsonObject!

Upvotes: 0

Alex Bean
Alex Bean

Reputation: 553

I would strongly recommend use the library Gson to parse a JSON document, is much easier and elegant.

public static date  parseJSON(String jsonArray) {
    date yourDate = new date();
    try {
        yourDate = (gson.fromJson(jsonArray, date.class));

    } catch (Exception e) {
        e.printStackTrace();
    }
    return yourDate;
}

Then the class date is just a class with the same elements that exists in the JSON you want to read in your case:

public class date {
    private String yesterday;
    private String today;
    private String tomorrow;

}

Upvotes: 2

Related Questions