ASP.Net 核心 c# 使用Microsoft图形导入 JSON 文件并将其转换为类



我需要通过守护程序服务从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; }
}   

我在NewtonSoft序列化JSON片段的文档中找到了答案

首先你得到 JsonString en 将其转换为 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);

}

最新更新