C# 如何轻松操作json
我有以下返回json的代码C# 如何轻松操作json,c#,asp.net,json,asp.net-mvc,C#,Asp.net,Json,Asp.net Mvc,我有以下返回json的代码 public async Task<ActionResult> GetPropertiesForUser() { Uri serviceRoot = new Uri(SettingsHelper.AzureAdGraphApiEndPoint); var token = await GetAppTokenAsync(); ActiveDirectoryClient a
public async Task<ActionResult> GetPropertiesForUser()
{
Uri serviceRoot = new Uri(SettingsHelper.AzureAdGraphApiEndPoint);
var token = await GetAppTokenAsync();
ActiveDirectoryClient adClient = new ActiveDirectoryClient(
serviceRoot,
async () => await GetAppTokenAsync());
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
Microsoft.Azure.ActiveDirectory.GraphClient.Application app = (Microsoft.Azure.ActiveDirectory.GraphClient.Application)adClient.Applications.Where(
a => a.AppId == SettingsHelper.ClientId).ExecuteSingleAsync().Result;
if (app == null)
{
throw new ApplicationException("Unable to get a reference to application in Azure AD.");
}
string requestUrl = string.Format("https://graph.windows.net/xx.onmicrosoft.com/users/{0}?api-version=1.5", ClaimsPrincipal.Current.Identities.First().Name);
HttpClient hc = new HttpClient();
hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
"Bearer", token);
HttpResponseMessage hrm = await hc.GetAsync(new Uri(requestUrl));
if (hrm.IsSuccessStatusCode)
{
string jsonresult = await hrm.Content.ReadAsStringAsync();
return View("GetPropertiesForUser", new SuccessViewModel
{
Name = "The Title",
Message = "The message",
JSON = jsonresult.ToJson()
});
}
else
{
return View();
}
}
如何将该JSON对象转换为强类型对象,或者如何轻松获取(例如)仅显示名称并将其返回到视图?您可以使用它为JSON生成类。
也可以使用Visual studio的内置功能:
编辑->粘贴特殊->将JSON粘贴为类
然后,您可以使用一些Json库来解析字符串,并将其作为对象使用(来自网站的示例):
stringjson=@”{
“名字”:“坏男孩”,
“发布日期”:“1995-4-7T00:00:00”,
“流派”:[
“行动”,
“喜剧”
]
}";
Movie m=JsonConvert.DeserializeObject(json);
{
"odata.metadata": "https://graph.windows.net/mysaasapp.onmicrosoft.com/$metadata#directoryObjects/Microsoft.DirectoryServices.User/@Element",
"odata.type": "Microsoft.DirectoryServices.User",
"objectType": "User",
"objectId": "058aac64-b821-4401-85ce-aa5f96514a52",
"deletionTimestamp": null,
"accountEnabled": true,
"assignedLicenses": [],
"assignedPlans": [],
"city": null,
"companyName": null,
"country": null,
"creationType": null,
"department": null,
"dirSyncEnabled": null,
"displayName": "Andrez Perez",
"facsimileTelephoneNumber": null,
"givenName": "Andres",
"immutableId": null,
"jobTitle": null,
"lastDirSyncTime": null,
"mail": null,
"mailNickname": "usuario1",
"mobile": null,
"onPremisesSecurityIdentifier": null,
"otherMails": [],
"passwordPolicies": "None",
"passwordProfile": null,
"physicalDeliveryOfficeName": null,
"postalCode": null,
"preferredLanguage": null,
"provisionedPlans": [],
"provisioningErrors": [],
"proxyAddresses": [],
"sipProxyAddress": null,
"state": null,
"streetAddress": null,
"surname": "Perez",
"telephoneNumber": null,
"usageLocation": null,
"userPrincipalName": "usuario1@xx.onmicrosoft.com",
"userType": "Member",
"extension_33e037a7b1aa42ab96936c22d01ca338_Compania": "Empresa1"
}
string json = @"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00',
'Genres': [
'Action',
'Comedy'
]
}";
Movie m = JsonConvert.DeserializeObject<Movie>(json);