【问题标题】:How to parse strange json object from api in C#如何在 C# 中从 api 解析奇怪的 json 对象
【发布时间】:2016-12-14 14:49:16
【问题描述】:

我正在使用一个 azure 移动应用程序,它以我无法读取的格式返回 json 数据。 刺痛是使用

var newMember = new Member() { Id = Settings.UserId };
var url = azureService.Client.MobileAppUri + ".auth/me";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-ZUMO-AUTH", Settings.AuthToken);
var response = await client.GetAsync(new Uri(url));
response.EnsureSuccessStatusCode();
dynamic responseBody = await response.Content.ReadAsStringAsync();

responseBody 是

"[
  {
    \"id_token\": \"tokenstring\",
    \"provider_name\": \"aad\",
    \"user_claims\": [
      {
        \"typ\": \"exp\",
        \"val\": \"903i4231\"
      },
      {
        \"typ\": \"nbf\",
        \"val\": \"123516345294\"
      },
      {
        \"typ\": \"ver\",
        \"val\": \"1.0\"
      },
      {
        \"typ\": \"iss\",
        \"val\": \"https: \\\/\\\/login.microsoftonline.com\\\/somestring\\\/v2.0\\\/\"
      },
      {
        \"typ\": \"http: \\\/\\\/schemas.xmlsoap.org\\\/ws\\\/2005\\\/05\\\/identity\\\/claims\\\/nameidentifier\",
        \"val\": \"someotherstring\"
      },
      {
        \"typ\": \"aud\",
        \"val\": \"anotherstringstill\"
      },
      {
        \"typ\": \"nonce\",
        \"val\": \"stringy\"
      },
      {
        \"typ\": \"iat\",
        \"val\": \"3543345\"
      },
      {
        \"typ\": \"http: \\\/\\\/schemas.microsoft.com\\\/ws\\\/2008\\\/06\\\/identity\\\/claims\\\/authenticationinstant\",
        \"val\": \"6363456345\"
      },
      {
        \"typ\": \"http: \\\/\\\/schemas.xmlsoap.org\\\/ws\\\/2005\\\/05\\\/identity\\\/claims\\\/givenname\",
        \"val\": \"FIRSTNAME?\"
      },
      {
        \"typ\": \"http: \\\/\\\/schemas.xmlsoap.org\\\/ws\\\/2005\\\/05\\\/identity\\\/claims\\\/surname\",
        \"val\": \"LastName?\"
      },
      {
        \"typ\": \"http: \\\/\\\/schemas.microsoft.com\\\/identity\\\/claims\\\/identityprovider\",
        \"val\": \"google.com\"
      },
      {
        \"typ\": \"http: \\\/\\\/schemas.microsoft.com\\\/identity\\\/claims\\\/objectidentifier\",
        \"val\": \"somestringelse\"
      },
      {
        \"typ\": \"emails\",
        \"val\": \"address@gmail.com\"
      },
      {
        \"typ\": \"tfp\",
        \"val\": \"B2C_1_ScoreSignupIn\"
      }
    ],
    \"user_id\": \"useridstring\"
  }
]"

如何将其转换为有用的 C# 对象,以便获取字符串 Firstname?LASTNAME?

我试过了

string firstName = responseJson.claims.givenname;

无济于事。 另外,这种类型的 JSON 叫什么。我记得在学习 azure API 时读过它,但我不记得在哪里。我什至不知道该怎么称呼它来搜索它。 jsonprettyprint.com 处的 json 漂亮打印,但我无法使用 http://json2csharp.com/ 将其转换为 C# 对象

【问题讨论】:

  • 实际消息是有效的 json 我更改了那里的值,因为它在我被删除的地方到处都是令牌。我会尝试再次编辑它,以便 json 有效。
  • 您无法转换为解析此 json 并将其转换为对象,对吧?
  • 当我试图从中删除私有数据时,这个特定的对象被破坏了。但是,编译器在解析来自服务器的响应时不会抱怨。我只是不明白如何从对象中获取数据。
  • 使用 Newtonsoft Nuget 包并尝试@Mohit 作为答案发布的方式。
  • 成功了,谢谢。我仍然不明白这个 json 的格式。是所有/ 转义字符还是什么?

标签: c# json azure


【解决方案1】:

您可以Install-Package Newtonsoft.Json 然后这就是您可以从 JSON 中查找值的方法

string jsn = File.ReadAllText("YourJSON.txt");
List<RootObject> ro = JsonConvert.DeserializeObject<List<RootObject>>(jsn);
foreach(UserClaim uc in ro[0].user_claims)
{
    if(uc.val=="FIRSTNAME")
    {
        //Do whatever you want.
    }
    //or
    if(uc.typ.Contains("givenname"))
    {
        Console.WriteLine(uc.val);
    }


}

这将是您的 JSON 的类

public class UserClaim
{
    public string typ { get; set; }
    public string val { get; set; }
}

public class RootObject
{
    public string id_token { get; set; }
    public string provider_name { get; set; }
    public List<UserClaim> user_claims { get; set; }
    public string user_id { get; set; }
}

【讨论】:

  • 这正是我所需要的。谢谢。
【解决方案2】:

请试试这个

JavaScriptSerializer serializer = new JavaScriptSerializer(); 

dynamic item = serializer.Deserialize<object>("{ \"test\":\"some data\" }");

string test= item["test"];

替换这个

"{ \"test\":\"一些数据\" }"

使用您的 JSON 字符串。

您还可以指定确切的数据类型,而不是对象和动态变量。

【讨论】:

  • 即使 Mohit 的解决方案有效,我也想尝试您的建议以更好地理解这一点。通过您的建议,是否可以在不循环的情况下获得如此复杂对象的值?
  • 产生了错误 System.ArgumentException: Accessed JArray values with invalid key value: "user_claims". Array position index expected. 我使用了 JsonConvert.DeserializeObject&lt;object&gt;() 因为我找不到名为 JavascriptSerializer 的对象。
  • 我的意思是你应该尝试写“List ro = JsonConvert.DeserializeObject>(jsn);”用“RootObject”代替动态,用List代替对象。
  • 这一行与 mohit 提到的相同。 :)
  • 哦,好的。 ``System.Collections.Generic.List.this[int]' has some invalid arguments`是这次的结果。你确定你最后一点没有考虑 Javascript 吗?我知道您可以在 JS 中使用数组表示法访问对象属性,但它似乎不适用于 C#。
猜你喜欢
  • 2015-11-05
  • 1970-01-01
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多