Charles de M.
Charles de M.

Reputation: 693

ASP.Net Core c# Importing a JSON File using Microsoft Graph and convert it to a Class

I need to get User Data from AAD (Azure Active Directory) through a daemon service. I have succeeded getting authorization and have downloaded the required userdata.

I cannot seem to get the data from the JSON file in a View. I have created a Model mimicking the JSON Properties. I get the JSON data as follows: string rawJson = await response.Content.ReadAsStringAsync(); When I try to deserialize it with GebruikersCollectie gebruikerscollectie = JsonConvert.DeserializeObject<GebruikersCollectie>(rawJson);, the result remains empty. I suspect the problem is in the '@data.context' property, but, I do not know how to solve this. The JSON file is as follows. How do I filter just the userdata and avoid the @odata.context?

{
{  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users", "value": 
[
{
"businessPhones": [],
"displayName": "John Doe", 
"givenName": "John",      
"jobTitle": "Owner",
"mail": "[email protected]",  
"mobilePhone": "+1 9 87654321", 
"officeLocation": Dullsville,      
"preferredLanguage": "en-US",
"surname": "Doe",
"userPrincipalName": "[email protected]",  
"id": "GUID number"    }, 

{      
"businessPhones": [],
"displayName": "SDK Test User", 
"givenName": null,  
"jobTitle": null,   
"mail": null,   
"mobilePhone": null, 
"officeLocation": null, 
"preferredLanguage": null, 
"surname": null, 
"userPrincipalName": "[email protected]", 
"id": "GUID"    } 
]
}}

My code is as follows: For my Index Controller:

public async Task<IActionResult> Index(string[] args)
    {
        // **************** Regel Authorisation *************************
        // Authorisation and token acquisition removed for simplicity
       //    {     ViewBag.TokenAcquired = "Token acquired";   

            if (result != null)
            {                    
                var httpClient = new HttpClient();
                var apiCaller = new ProtectedApiCallHelper(httpClient);
                await apiCaller.CallWebApiAndProcessResultASync("https://graph.microsoft.com/v1.0/users", result.AccessToken, Display);                    
                return View();                    
            }
        }            
        return View();
    }

private static void Display(GebruikersCollectie gebruikerscollectie)
    {

        View(gebruikerscollectie);                        


    }

The Method to get the JSON data is as follows:

public async Task CallWebApiAndProcessResultASync(string webApiUrl, string accessToken, Action<GebruikersCollectie> processResult)
    {
        if (!string.IsNullOrEmpty(accessToken))
        {
            var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
            if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
            {
                HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));                    
            }
            defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
            HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
            if (response.IsSuccessStatusCode)
            {                    
                string rawJson = await response.Content.ReadAsStringAsync();                    
                GebruikersCollectie gebruikerscollectie = JsonConvert.DeserializeObject<GebruikersCollectie>(rawJson);
                processResult(gebruikerscollectie);                 
            }

And here are the Models:

public class GebruikersCollectie
{
    public List<Gebruiker> gebruikers { get; set; }
}

public class Gebruiker
{

    public List<int> businessPhones { get; set; }        
    public string displayName { get; set; }
    public string givenName { get; set; }
    public string jobTitle { get; set; }
    public string mail { get; set; }
    public string mobilePhone { get; set; }
    public string officeLocation { get; set; }
    public string preferredLanguage { get; set; }
    public string surname { get; set; }
    public string userPrincipalName { get; set; }
    public string id { get; set; }
}   

Upvotes: 1

Views: 1045

Answers (1)

Charles de M.
Charles de M.

Reputation: 693

I have found the answer in the documentation of NewtonSoft Serializing JSON Fragments

First you get the JsonString en convert it to a JObject

string rawJson = await response.Content.ReadAsStringAsync();
JObject jsonResult = JsonConvert.DeserializeObject(rawJson) as JObject;

In the Callback method from the apicaller you convert it to a .Net object with the help of JToken That is all.

Now I need to find a way to get it into a View. As the current method is void I need to find a way to get that working. Please comment on any thoughts.

private static void ZetKlaar(JObject jsonResult)
    {

        IList<JToken> resultaten = jsonResult["value"].Children().ToList();



        IList<Gebruiker> gebruikers = new List<Gebruiker>();            
        foreach (JToken resultaat in resultaten)
        {
            Gebruiker gebruiker = resultaat.ToObject<Gebruiker>();
            gebruikers.Add(gebruiker);
            //collectie.gebruikers.Add(gebruiker);                
        }

        Console.WriteLine(gebruikers);


    }

Upvotes: 1

Related Questions