【问题标题】:Deserialize ever changing JSON object name in C#在 C# 中反序列化不断变化的 JSON 对象名称
【发布时间】:2017-04-15 16:24:33
【问题描述】:

我请求的端点:

https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=eminem

如果您查看 Pages 对象中的 JSON,则会发现另一个对象,它是维基百科文章的 id。在我的项目中,我不仅会解析 Eminem 的页面,还会解析其他歌手/艺术家。所以我的问题是如何去解析这个不断变化的 json 对象名称?

我的 json 作为 c# 类

public class ArticleRootobject {
    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 _4429395 _4429395 { get; set; }
}

public class Normalized{
    public string from { get; set; }
    public string to { get; set; }
}

感谢您的帮助

【问题讨论】:

标签: c# asp.net json json.net


【解决方案1】:

根据您用于反序列化的库,您可以将 Query 上的 Pages 属性声明为Dictionary<string,[contentObject]>。您需要使用相关属性(pageId、ns、title 等)为 contentObject 创建一个类。

http://www.newtonsoft.com/json/help/html/DeserializeDictionary.htm

【讨论】:

    【解决方案2】:

    您可以将Querypages 属性定义为Dictionary<string, Page>,并为Page 定义一个类:

    public class Query
    {
        public Normalized[] normalized { get; set; }
        public Dictionary<string, Page> pages { get; set; }
    }
    
    public class Page
    {
        public int pageid { get; set; }
        public int ns { get; set; }
        public string title { get; set; }
        public string extract { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多