c# - 如何使用 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
解决方案
您将需要一个类来模拟像这样返回的对象。
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);
祝你好运!
推荐阅读
- python - ValueError:形状(259,2)和(1,33)未对齐:2(dim 1)!= 1(dim 0)
- python - 找不到从终端运行的 Python 模块
- ruby-on-rails - 以一种方式加入,但不是另一种
- visual-studio - 无法使用 MSBuild 的 UnZip 任务解压缩包含文件夹的 zip 文件
- cypress - 比较 datetime 函数 cypress
- python - scikit learn Pipeline 是否将 StandardScaler 应用于 y?
- android - Android 架构蓝图 [todo-mvp-dagger] @ActivityScoped, @FragmentScoped
- typescript - 如何在没有框架的情况下使用 Typescript?
- c - 当你只需要 1 位时,充分利用 256 个随机位
- css - Wordpress 网站标题在滚动页面元素后面移动