从JSON字符串中检索值

时间:2016-12-27 03:27:44

标签: c# json

我正在尝试使用返回的Key中的JSON来检索string email= json.emailAddress;

我尝试了以下但没有效果。

1)

string email= json["emailAddress"].ToString();

2)。

 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);
  }

完整代码

{
  "emailAddress": "xxxx@xx.com",
  "firstName": "xxx",
  "formattedName": "xxxx xxxx",
  "id": "xxxxxx",
  "lastName": "xxxxxx",

}

JSON返回

$yourArray = array(
   'sku_name',
   'price',
   'typesku_'
);

$replaced = array_map(
    function($val)
    {
        if (stripos($val, "sku_") === 0)
        {
            return substr($val, 4);
        }
        return $val;
    },
    $yourArray
);

print_r($replaced);

3 个答案:

答案 0 :(得分:4)

要使用您的方法回答您的问题,最简单的方法(不使用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 库进行反序列化。

答案 1 :(得分:3)

您可以安装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);

答案 2 :(得分:1)

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;
  ...
}
相关问题