从JSON中的数据中提取所有值

时间:2017-11-16 00:44:59

标签: c# json

我在"data"中有多个电影标题的回复。有没有办法快速提取它们?我需要一个只有电影片名的数组。

{
  "page": "2",
  "per_page": 10,
  "total": 13,
  "total_pages": 2,
  "data": [{
    "Poster": "N/A",
    "Title": "They Call Me Spiderman",
    "Type": "movie",
    "Year": 2016,
    "imdbID": "tt5861236"
  }, {
    "Poster": "N/A",
    "Title": "The Death of Spiderman",
    "Type": "movie",
    "Year": 2015,
    "imdbID": "tt5921428"
  }, {
    "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw@@._V1_SX300.jpg",
    "Title": "Spiderman in Cannes",
    "Type": "movie",
    "Year": 2016,
    "imdbID": "tt5978586"
  }]
}

3 个答案:

答案 0 :(得分:1)

您可以使用:

这样:

dynamic content = JsonConvert.DeserializeObject<ExpandoObject>(data);

这样的事情:

using System;
using System.Dynamic;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        string data = @"{
  'page': '2',
  'per_page': 10,
  'total': 13,
  'total_pages': 2,
  'data': [{
    'Poster': 'N/A',
    'Title': 'They Call Me Spiderman',
    'Type': 'movie',
    'Year': 2016,
    'imdbID': 'tt5861236'
  }, {
    'Poster': 'N/A',
    'Title': 'The Death of Spiderman',
    'Type': 'movie',
    'Year': 2015,
    'imdbID': 'tt5921428'
  }, {
    'Poster': 'https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw@@._V1_SX300.jpg',
    'Title': 'Spiderman in Cannes',
    'Type': 'movie',
    'Year': 2016,
    'imdbID': 'tt5978586'
  }]
}";
        dynamic content = JsonConvert.DeserializeObject<ExpandoObject>(data);
        int i;
        int len = content.data.Count;
        string result = "";
        string[] myArray;
        for (i = 0; i < len; i++)
        {
            result += content.data[i].Title; // Extract the movie title.
            result += ","; // Conact with commas.
        }

        result = result.Substring(0, result.Length - 1);
        myArray = result.Split(','); // Array of string with the movie titles.
        Console.WriteLine(myArray[0]);
    }
}

请参阅操作:.NET Fiddle

答案 1 :(得分:0)

var data = new Dictionary<string, string>();
data.Add("foo", "baa"); 

JavaScriptSerializer ser = new JavaScriptSerializer();
var JSONString = ser.Serialize(data); //JSON encoded

var JSONObj = ser.Deserialize<Dictionary<string, string>>(JSONString); //JSON decoded
Console.Write(JSONObj["foo"]); //prints: baa

答案 2 :(得分:0)

使用Newtonsoft.Json.Linq可能会为您做最简单的工作。

using Newtonsoft.Json.Linq;

List<string> movieTitles = (JObject.Parse(json)["data"]).
                   Cast<JToken>().Select(x => x["Title"].ToString()).ToList();