简体   繁体   English

如何轻松操作json

[英]how to manipulate json easily

I have the following code that returns me a json 我有以下代码返回一个json

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

And the json is like this: 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"
}

How can I convert that JSON object into a strongly typed object, or how can I get easily for example the display name only and return it to the View? 如何将JSON对象转换为强类型对象,或者如何轻松获取例如显示名称并将其返回到View?

You can use http://json2csharp.com/ to generate classes for your json. 您可以使用http://json2csharp.com/为json生成类。 Or you can use built-in functionality of Visual studio: 或者,您可以使用Visual Studio的内置功能:

Edit->Paste special->Paste JSON as classes 编辑->粘贴特殊->粘贴JSON作为类

Then you can use some Json library like http://www.newtonsoft.com/json to parse your string and work with it as object (example from website): 然后,您可以使用一些http://www.newtonsoft.com/json之类的Json库来解析您的字符串并将其作为对象使用(来自网站的示例):

string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
    'Action',
    'Comedy'
  ]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM