我正在使用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 prettyprints,但我无法使用http://json2csharp.com/将其转换为C#对象
答案 0 :(得分:3)
你可以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; }
}
答案 1 :(得分:0)
请试试这个
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>("{ \"test\":\"some data\" }");
string test= item["test"];
替换此
“{\”test \“:\”some data \“}”
使用您的JSON字符串。
您还可以指定确切的数据类型,而不是对象和动态变量。