marcusstarnes
marcusstarnes

Reputation: 6531

Retrieve boolean value from json data containing string key/values

I have the following json data being returned to me and I need to check if the user has the 'public_actions' permission granted or not.

{"data":[{"permission":"installed","status":"granted"},{"permission":"public_profile","status":"granted"},{"permission":"email","status":"granted"},{"permission":"publish_actions","status":"granted"}]}

Having not really done anything with json data before, I'm not sure the recommended approach to essentially arrive at a true or false (whether that particular permission has been granted or not).

Upvotes: 0

Views: 728

Answers (1)

Hassan
Hassan

Reputation: 5430

Json.NET is a popular high-performance JSON framework for .NET.

This how I read json string using Newtonsoft.Json.dll:

var json = @"{
               data: [
                       {
                          permission: 'installed',
                          status: 'granted'      
                       },
                       {
                          permission: 'public_profile',
                          status: 'granted'      
                       },
                       {
                          permission: 'email',
                          status: 'granted'      
                       },
                       {
                          permission: 'publish_actions',
                          status: 'granted'      
                       }
                     ]
             }";

JObject jObjects = JObject.Parse(json);

foreach (KeyValuePair<String, JToken> kvpParent in jObjects)
{
     var sMainKey = kvpParent.Key;
     var objects = JArray.Parse(kvpParent.Value.ToString());

     foreach (JObject jObj in objects)
     {
          foreach (KeyValuePair<String, JToken> kvp in jObj)
          {
                var sKey = kvp.Key;    //permission
                var sValue = (String)kvp.Value; //installed                       
          }
     }
}

Each KeyValuePair gets 2 count that is for permission and status keys.

Upvotes: 1

Related Questions