【问题标题】:Retrieving value from a JSON string从 JSON 字符串中检索值
【发布时间】:2016-12-27 11:51:54
【问题描述】:

我正在尝试使用返回的JSON 中的Key 检索Value

我尝试了以下方法,但都没有成功。

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",

}

【问题讨论】:

  • 有些时候dynamic 很好用,但是当您知道方法的返回类型时,您应该声明该类型的变量,即string json = webClient.DownloadString(api);。使用dynamic 不会给你的变量带来神奇的属性——如果它是string,它仍然是stringdynamic

标签: c# json


【解决方案1】:

要使用您的方法回答您的问题,最简单的方法(不使用 JSON.Net)是使用 JavaScriptSerializer

// have this at the top with your using statements
using System.Web.Script.Serialization;

并在您的代码中使用JavaScriptSerializer,如下所示。

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 库进行反序列化。

【讨论】:

  • 这里给出的所有答案都很完美。你认为@Mohit 的回答是最好的方法吗?
【解决方案2】:

您可以安装 Newtonsoft Json.Net 以从 JSON 字符串中检索值。您可以简单地创建类,如

public class Rootobject
{
    public string emailAddress { get; set; }
    public string firstName { get; set; }
    public string formattedName { get; set; }
    public string id { get; set; }
    public string lastName { get; set; }
}

然后用简单的一行代码反序列化它。

var ser = JsonConvert.DeserializeObject<Rootobject>(YourJsonString);
Console.WriteLine(ser.emailAddress);

【讨论】:

  • 感谢您的回复。您的解决方案同样有效。
【解决方案3】:
result={
         "emailAddress": "xxxx@xx.com",
         "firstName": "xxx",
         "formattedName": "xxxx xxxx",
         "id": "xxxxxx",
         "lastName": "xxxxxx"
        }
 var ser = new JavaScriptSerializer();
 var people = ser.Deserialize<object[]>(result);
foreach(var obj in people)
{
  Email = obj.emailAddress;
  ...
}

【讨论】:

  • 感谢您的回复。您的解决方案同样有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多