【问题标题】:ASP.Net Core c# Importing a JSON File using Microsoft Graph and convert it to a ClassASP.Net Core c# 使用 Microsoft Graph 导入 JSON 文件并将其转换为类
【发布时间】:2019-11-25 17:36:08
【问题描述】:

我需要通过守护程序服务从 AAD (Azure Active Directory) 获取用户数据。 我已成功获得授权并已下载所需的用户数据。

我似乎无法从视图中的 JSON 文件中获取数据。我创建了一个模仿 JSON 属性的模型。我得到如下 JSON 数据:string rawJson = await response.Content.ReadAsStringAsync(); 当我尝试用GebruikersCollectie gebruikerscollectie = JsonConvert.DeserializeObject<GebruikersCollectie>(rawJson); 反序列化它时,结果仍然是空的。我怀疑问题出在“@data.context”属性中,但是,我不知道如何解决。 JSON文件如下。如何仅过滤用户数据并避免 @odata.context?

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

{      
"businessPhones": [],
"displayName": "SDK Test User", 
"givenName": null,  
"jobTitle": null,   
"mail": null,   
"mobilePhone": null, 
"officeLocation": null, 
"preferredLanguage": null, 
"surname": null, 
"userPrincipalName": "sdk_test@Doe.onmicrosoft.com", 
"id": "GUID"    } 
]
}}

我的代码如下: 对于我的Index 控制器:

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);                        


    }

获取JSON数据的方法如下:

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);                 
            }

以下是模型:

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; }
}   

【问题讨论】:

  • GebruikersCollectie 模型很可能与 JSON 不匹配。你能分享那个模型吗——比如minimal reproducible example
  • @dbc 我已经包含了模型

标签: c# json asp.net-core microsoft-graph-api


【解决方案1】:

我在NewtonSoftSerializing JSON Fragments的文档中找到了答案

首先你得到 JsonString 并将其转换为 JObject

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

在 apicaller 的回调方法中,您可以在 JToken 的帮助下将其转换为 .Net 对象 就这些。

现在我需要找到一种方法将其放入视图中。由于目前的方法是无效的,我需要找到一种方法来让它发挥作用。请发表任何想法。

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);


    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多