如何从JSON文件中获取数据?

时间:2015-01-31 13:40:16

标签: c# json

我对编程有点新意,我有一个问题。我想从JSON文件中获取数据,但我不知道如何访问它。

这是JSON文件,我想要获取的数据是' uri'。

{
  "albums" : {
    "href" : "https://api.spotify.com/v1/search?query=elephant+the+white+stripes&offset=0&limit=1&type=album",
    "items" : [ {
      "album_type" : "album",
      "available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HN", "HU", "IE", "IS", "IT", "LI", "LT", "LU", "LV", "MC", "MX", "NI", "NL", "NO", "NZ", "PA", "PE", "PL", "PT", "PY", "RO", "SE", "SI", "SK", "SV", "TR", "UY" ],
      "external_urls" : {
        "spotify" : "https://open.spotify.com/album/0rRNLpdA8nA8Sm8Fk490b9"
      },
      "href" : "https://api.spotify.com/v1/albums/0rRNLpdA8nA8Sm8Fk490b9",
      "id" : "0rRNLpdA8nA8Sm8Fk490b9",
      "images" : [ {
        "height" : 618,
        "url" : "https://i.scdn.co/image/7c7667a66c195842a18341b754ddff1e57295774",
        "width" : 640
      }, {
        "height" : 290,
        "url" : "https://i.scdn.co/image/4d761858e1541ef386a0b8a9f1047805db754a6d",
        "width" : 300
      }, {
        "height" : 62,
        "url" : "https://i.scdn.co/image/7b5248fbae00aae3c9d6d01abb24b32578aa3f31",
        "width" : 64
      } ],
      "name" : "Elephant",
      "type" : "album",
      "uri" : "spotify:album:0rRNLpdA8nA8Sm8Fk490b9"
    } ],
    "limit" : 1,
    "next" : "https://api.spotify.com/v1/search?query=elephant+the+white+stripes&offset=1&limit=1&type=album",
    "offset" : 0,
    "previous" : null,
    "total" : 3
  }
}

到目前为止,这是我的代码,我将数据存储在href。

WebClient c = new WebClient();

var getData = c.DownloadString("https://api.spotify.com/v1/search?q=elephant%20the%20white%20stripes&type=album&limit=1");

JObject o = JObject.Parse(getData);

Console.WriteLine("href: " + o["albums"]["href"]);

2 个答案:

答案 0 :(得分:0)

  var result = o["albums"]["items"][0]["uri"];

uri在物品中,这里只有一件物品。如果还有更多,则必须更改[0]。

答案 1 :(得分:0)

您可以使用JSON.net(Nuget包here

var getData = c.DownloadString("https://api.spotify.com/v1/search?q=elephant%20the%20white%20stripes&type=album&limit=1");

dynamic data = JsonConvert.DeserializeObject(getData); // or JObject.Parse(getData)

Console.WriteLine(data.albums.items[0].uri);