首页 > 解决方案 > 如何使用 Newtonsoft.Json 获取特定字段

问题描述

我想得到所有结果

这是 API:

{
    "videos": {
        "results": [
            {
                "id": "5c8a4d5b0e0a267d08c32f18",
                "iso_639_1": "en",
                "iso_3166_1": "US",
                "key": "hA6hldpSTF8",
                "name": "Trailer",
                "site": "YouTube",
                "size": 1080,
                "type": "Trailer"
            },
            {
                "id": "5c8a4d740e0a26042bc441ef",
                "iso_639_1": "en",
                "iso_3166_1": "US",
                "key": "TcMBFSGVi1c",
                "name": "Trailer",
                "site": "YouTube",
                "size": 1080,
                "type": "Trailer"
            },
            {
                "id": "5c93af740e0a261053e9026d",
                "iso_639_1": "en",
                "iso_3166_1": "US",
                "key": "-iFq6IcAxBc",
                "name": "Big Game TV Spot",
                "site": "YouTube",
                "size": 1080,
                "type": "Teaser"
            }
        ]
    }
}

我的代码:

         public FormVerTrailer(string id)      
         {

            InitializeComponent();

             WebClient wc = new WebClient();

             string json = wc.DownloadString("https://api.themoviedb.org/3/movie/"+id+"? 
             api_key={ApiKey}&append_to_response=videos");

            richTextBox1.Text += json.ToString();

            GetVideo Videos = JsonConvert.DeserializeObject<GetVideo>(json);
        }

    class GetVideo
    {

        public object[] results { get; set; }
        public string key { get; set; }
    }

谢谢你!:D

标签: c#

解决方案


您将需要一个类来模拟像这样返回的对象。

    class JsonExample
    {
        [JsonProperty("id")]
        public string ID { get; set; }

        [JsonProperty("iso_639_1")]
        public string ISO6391 { get; set; }

        [JsonProperty("iso_3166_1")]
        public string ISO31661 { get; set; }

        [JsonProperty("key")]
        public string Key { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("site")]
        public string Site { get; set; }

        [JsonProperty("size")]
        public int Size { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }

        //This would be in your main class not your model but for brevity..
        public static List<JsonExample> GetListOfObjects (string json)
        {
            return JsonConvert.DeserializeObject<List<JsonExample>>(json);
        }
    }

然后像这样获取您的数组/列表。

var data = "Get your data here";
var list = JsonExample.GetListOfObjects(data);

祝你好运!


推荐阅读