简体   繁体   中英

Parsing JSON Array Children properties in android

Here is the ASP .net code for Extracting a JSON Array:

{
"Attendance": {
"FirstName": "Test1"
"InTime": "12:32:00"
"LastName": "User"
"OutTime": "12:38:11"
}
{
"FirstName": "Test2"
"InTime": "12:26:59"
"LastName": "User"
"OutTime": "12:38:19"
}

}



 JObject o = JObject.Parse(jsonString);
        JArray arr = (JArray)o.SelectToken("Attendance");

        foreach (JObject b in arr.Children<JObject>())
        {
            foreach (JProperty p in b.Properties())
            {
                string name = p.Name;
                string value = p.Value.ToString();
                //  Console.WriteLine(name + ": " + value);
                System.Diagnostics.Debug.WriteLine("" + name + ": " + value);
            }
        }

Above Code will extract its Name and Value Instead of passing Name and returning Value which we do using JSONOBJECT.

// System.Diagnostics.Debug.WriteLine("" + name + ": " + value);
FirstName: Test1
InTime: 12:32:00
LastName: User
OutTime: 12:38:11
FirstName: Test2
InTime: 12:26:59
LastName: User
OutTime: 12:38:19

How can I achieve same functionality in Android ?

Using this json.org library for Java , you can use the code below translated to Java and ready to use in Android. For logging purposes you should replace System.out with Log.d

import org.json.*;

JSONObject o = new JSONObject(jsonString);
JSONArray arr = obj.getJSONArray("Attendance");
for (int i = 0; i < arr.length(); i++)
{
   JSONObject b = arr.getJSONObject(i);
   Iterator<?> keys = b.keys();    
   while( keys.hasNext() ) {
       String key = (String)keys.next();
       System.out.println(key+": "+b.get(key).toString());   

   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM