从JSON字符串中检索值 [英] Retrieving value from a JSON string

查看:124
本文介绍了从JSON字符串中检索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用返回的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆