Armin Orlik
Armin Orlik

Reputation: 195

Parse a JSON-string in Android

Right now I have the following JSON string:

"{"1":{"from":"540","to":"1020"},"2":{"from":"540","to":"1020"},"3":{"from":"540","to":"1020"},"4":{"from":"540","to":"1020"},"5":{"from":"540","to":"1020"},"6":{"from":"540","to":"1020"},"7":{"from":"540","to":"1020"}}"

and I want to parse it in Android Studio and iterate all just for this kind of result:

String day = monday;
int hourstart = from;
int hoursclose = to;

of course from and to means numbers. Does anyone know how construction of a JSON parser should look like?

Upvotes: 1

Views: 53

Answers (1)

Aakash
Aakash

Reputation: 5251

Try this:

           //here jsonString is your json in string format

           JSONObject obj3=new JSONObject(jsonString);
           JSONObject obj4=null;
           //Getting all the keys inside json object with keys- from and to
              Iterator<String> keys= obj3.keys();
              while (keys.hasNext()) 
             {
                   String keyValue = (String)keys.next();
                   obj4 = obj3.getJSONObject(keyValue);
                   //getting string values with keys- from and to
                   String from = obj4.getString("from");
                   String to = obj4.getString("to");
                   int hourstart = Integer.parseInt(from);
                   int hoursclose = Integer.parseInt(to);
                   System.out.println("From : "+ hourstart +" To : "+ hoursclose);
             }

Upvotes: 2

Related Questions