Search code examples
c#jsonlistjson-deserialization

Extract value from Json format in C#


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%20eq%20'{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": "alt_sachint@pme.gbl.msidentity.com"
        }
      ]
    }}

Solution

  • 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