【发布时间】:2020-10-17 05:12:56
【问题描述】:
我正在尝试使用 wikimedia API 从 wikipedia 文章中查询最重要的信息。在我的代码中,我有以下行:
WikiArticleModel article = await response.Content.ReadAsAsync<WikiArticleModel>().ConfigureAwait(false);
这是我的 JSON 对象在对木星行星上的文章进行测试时的外观示例:
{
"batchcomplete": "",
"query": {
"normalized": [
{
"from": "jupiter",
"to": "Jupiter"
}
],
"pages": {
"38930": {
"pageid": 38930,
"ns": 0,
"title": "Jupiter",
"extract": ">>> Her comes the first section of the article, which I deleted to make
this shorter <<<",
"description": "Fifth planet from the Sun and largest planet in the Solar System",
"descriptionsource": "local",
"original": {
"source": "https://upload.wikimedia.org/wikipedia/commons/2/2b/Jupiter_and_its_shrunken_Great_Red_Spot.jpg",
"width": 940,
"height": 940
}
}
}
}
}
现在的问题是,我的WikiArticleModel 班级应该是什么样子?也使用内置的 VS Studio “将 JSON 粘贴为类”,我得到以下结果:
public class WikiArticleModel
{
public string batchcomplete { get; set; }
public Query query { get; set; }
}
public class Query
{
public Normalized[] normalized { get; set; }
public Pages pages { get; set; }
}
public class Pages
{
public _38930 _38930 { get; set; }
}
public class _38930
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public string extract { get; set; }
public string description { get; set; }
public string descriptionsource { get; set; }
public Original original { get; set; }
}
public class Original
{
public string source { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Normalized
{
public string from { get; set; }
public string to { get; set; }
}
除了 _38930 类之外,这是可以的,我期望的是,它只是 pageid 并且会随着每个查询而改变。
反序列化此对象的正确方法是什么?或者在这种情况下,仅获取 object 作为响应并手动填充模型类是更好的方法吗?
此外,我实际上只需要来自JSON 对象的某些参数(例如标题、提取、描述等) - 有没有办法将这些参数直接放入仅包含我需要的属性的模型类中?
【问题讨论】:
标签: c# json api serialization