从JSON字符串中检索值 [英] Retrieving value from a JSON string
问题描述
我正在尝试使用返回的JSON
中的Key
来检索Value
.
I am trying to retrieve Value
's using Key
's in the JSON
returned.
我尝试了以下方法,但是没有用.
I tried the following but, none worked.
1.)
string email= json.emailAddress;
2.)
string email= json["emailAddress"].ToString();
完整代码
var api= new Uri("https://api.linkedin.com/v1/people/~:(picture-url)?format=json");
using (var webClient = new WebClient())
{
webClient.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
webClient.Headers.Add("x-li-format", "json");
dynamic json = webClient.DownloadString(api);
}
JSON返回
{
"emailAddress": "xxxx@xx.com",
"firstName": "xxx",
"formattedName": "xxxx xxxx",
"id": "xxxxxx",
"lastName": "xxxxxx",
}
推荐答案
要使用您的方法回答您的问题,最简单的方法(不使用JSON.Net)是使用JavaScriptSerializer
To answer your question using your approach, the simplest way ( without using JSON.Net ) is to use the JavaScriptSerializer
// have this at the top with your using statements
using System.Web.Script.Serialization;
并在您的代码中,如下所示使用JavaScriptSerializer
.
and in your code, use JavaScriptSerializer
as shown below.
var api= new Uri("https://api.linkedin.com/v1/people/~:(picture-url)?format=json");
using (var webClient = new WebClient())
{
webClient.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
webClient.Headers.Add("x-li-format", "json");
string json = webClient.DownloadString(api);
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic data = serializer.Deserialize<object[]>(json);
string emailAddress = data.emailAddress;
}
更好的方法是使用 http://json2csharp.com之类的东西为返回的JSON数据创建强类型的POCO. /,然后使用 JSON.Net 库反序列化.
The better way would be to create strong-typed POCOs for your return JSON data using something like http://json2csharp.com/ and then deserializing using JSON.Net Library.
这篇关于从JSON字符串中检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!