Home > database >  Extract value from Json format in C#
Extract value from Json format in C#

Time:11-20

I am trying to extract the objectId and displayName from below JSON format http result. But I have not been successful at all. can someone suggest me to extract objectId and displayName.

My code so far:

 var httpClient = new HttpClient
{
    BaseAddress = new Uri("https://graph.windows.net/")
};
string URI = $"/{TenantID}/users?$filter=userPrincipalName eq '{EmailAddress}'&api-version=1.6";
httpClient.DefaultRequestHeaders.Remove("Authorization");
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer "   MSGraphToken);
HttpResponseMessage response = await httpClient.GetAsync(URI).ConfigureAwait(false);
var HttpsResponse = await response.Content.ReadAsStringAsync();
dynamic Result = JsonConvert.DeserializeObject<object>(HttpsResponse);
UserDetails UserDetailsList = new UserDetails();
dynamic OdataResult = Result["value"];

if (Result != null)
{
    UserDetailsList.DisplayName = OdataResult.displayName ?? "N/A";
    UserDetailsList.ObjectID = OdataResult.objectId ?? "N/A";
}
return UserDetailsList;

JSON result:

{{
      "value": [
        {
          "odata.type": "Microsoft.DirectoryServices.User",
          "objectType": "User",
          "objectId": "00000000-0000-0000-0000-000000000000",
          "assignedPlans": [
            {
              "assignedTimestamp": "2022-09-06T20:38:49Z",
              "capabilityStatus": "Enabled",
              "service": "RMSOnline",
              "servicePlanId": "00000000-0000-0000-0000-000000000000"
            },
            {
              "assignedTimestamp": "2022-09-06T20:38:49Z",
              "capabilityStatus": "Enabled",
              "service": "Adallom",
              "servicePlanId": "00000000-0000-0000-0000-000000000000"
            },        
          ],
          "displayName": "Sachin Tendulkar (alt_sachint)",
          "employeeId": "000000",          
          "userPrincipalName": "[email protected]"
        }
      ]
    }}

CodePudding user response:

First of all your posted JSON is invalid, I have corrected it.

{
    "value": [{
        "odata.type": "Microsoft.DirectoryServices.User",
        "objectType": "User",
        "objectId": "00000000-0000-0000-0000-000000000000",
        "assignedPlans": [{
                "assignedTimestamp": "2022-09-06T20:38:49Z",
                "capabilityStatus": "Enabled",
                "service": "RMSOnline",
                "servicePlanId": "00000000-0000-0000-0000-000000000000"
            },
            {
                "assignedTimestamp": "2022-09-06T20:38:49Z",
                "capabilityStatus": "Enabled",
                "service": "Adallom",
                "servicePlanId": "00000000-0000-0000-0000-000000000000"
            }
        ],
        "displayName": "Sachin Tendulkar (alt_sachint)",
        "employeeId": "000000",
        "userPrincipalName": "[email protected]"
    }]

}

Then you should deserialize the json to a class object.

Root obj = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class AssignedPlan
{
    public DateTime assignedTimestamp { get; set; }
    public string capabilityStatus { get; set; }
    public string service { get; set; }
    public string servicePlanId { get; set; }
}

public class Root
{
    public List<Value> value { get; set; }
}

public class Value
{
    [JsonProperty("odata.type")]
    public string odatatype { get; set; }
    public string objectType { get; set; }
    public string objectId { get; set; }
    public List<AssignedPlan> assignedPlans { get; set; }
    public string displayName { get; set; }
    public string employeeId { get; set; }
    public string userPrincipalName { get; set; }
}

So you can get the List of Value by obj.value which is a List of Value. Value class has properties objectId and employeeId .

You can use foreach or for or LINQ to fetch these properties accordingly.

CodePudding user response:

just use Parse if you only need to get a couple of values. In this case you don't need to create classes

var json = await response.Content.ReadAsStringAsync();
var value = JObject.Parse(json)["value"];
string objectId = (string)value[0]["objectId"]; // 00000000-0000-0000-0000-000000000000
string displayName = (string)value[0]["displayName"]; // Sachin Tendulkar (alt_sachint)

and remove an extra "{ }" from the edges of your json

CodePudding user response:

you can get using dynamic also but i recommended to use strong type

Logic to get values

Using Strong Type

 private void ReadJson()
        {
            string json = @"{""value"":[{""odata.type"":""Microsoft.DirectoryServices.User"",""objectType"":""User"",""objectId"":""00000000 - 0000 - 0000 - 0000 - 000000000000"",""assignedPlans"":[{""assignedTimestamp"":""2022 - 09 - 06T20: 38:49Z"",""capabilityStatus"":""Enabled"",""service"":""RMSOnline"",""servicePlanId"":""00000000 - 0000 - 0000 - 0000 - 000000000000""},{""assignedTimestamp"":""2022 - 09 - 06T20: 38:49Z"",""capabilityStatus"":""Enabled"",""service"":""Adallom"",""servicePlanId"":""00000000 - 0000 - 0000 - 0000 - 000000000000""},],""displayName"":""Sachin Tendulkar(alt_sachint)"",""employeeId"":""000000"",""userPrincipalName"":""alt_sachint @pme.gbl.msidentity.com""}]}";
            var response = JsonConvert.DeserializeObject<Result>(json);

            var objid = response.value[0].objectId;
            var displayname = response.value[0].displayName;

            // using for loop 

            foreach( var res in response.value)
            {
                objid = res.objectId;
                displayname = res.displayName;
            }

            // you can use linq if you need object id and display name for specific condition

            
        }

Classes

public class Result
    {
        public List<Response> value { get; set; }
    }

public class Response
    {
        public string objectId { get; set; }

        public string displayName { get; set; }

        [JsonProperty("odata.type")]
        public string odatatype { get; set; }

        public string objectType { get; set; }

        public List<AssignedPlan> assignedPlans { get; set; }

        public string employeeId { get; set; }

        public string userPrincipalName { get; set; }
    }

    public class AssignedPlan
    {
        public DateTime assignedTimestamp { get; set; }
        public string capabilityStatus { get; set; }
        public string service { get; set; }
        public string servicePlanId { get; set; }
    }

using dynamic

// 2. using dynamic
            dynamic Result = JsonConvert.DeserializeObject<object>(json);
            JArray jsonObject = JArray.FromObject(Result["value"]);
            //JArray jsonObject = JArray.Parse(Result["value"]);
            foreach (JObject content in jsonObject.Children<JObject>())
            {
                // you can get value from one of the approach
                // 1. Approach
                foreach (JProperty prop in content.Properties().Where(p => p.Name == "objectId"))
                {
                    objid = prop.Value.ToString();
                }

                foreach (JProperty prop in content.Properties().Where(p => p.Name == "displayName"))
                {
                    displayname = prop.Value.ToString();
                }

                // 2. Apprach
                foreach (JProperty prop in content.Properties())
                {
                    if (prop.Name == "objectId")
                    {
                        objid = prop.Value.ToString();
                    }
                    else if(prop.Name == "displayName")
                    {
                        displayname = prop.Value.ToString();
                    }
                }

            }

you can get value by following @Serge answer using dynamic if it is always one object in response(value node) but as per your sample it is array so you need to use Jarray or loop to get each value.

  • Related