【问题标题】:C# JSON to class [duplicate]C# JSON 到类 [重复]
【发布时间】:2019-08-01 04:32:55
【问题描述】:

我想将数据从 IMDB.com 解析到我的 c# 应用程序。我有一个名为 IMDB_Entry 的类,如下所示:

private string type;
    private string url;
    private string name;
    private string image;
    private List<String> genre;
    private string content_rating;
    private List<IMDB_Entry> actors;
    private List<IMDB_Person> directors;
    private List<IMDB_Person> creators;
    private string description;
    private string date;
    private List<String> keywords;
    private IMDB_Rating rating;
    private string duration;

    public string Type { get => type; set => type = value; }
    public string Url { get => url; set => url = value; }
    public string Name { get => name; set => name = value; }
    public string Image { get => image; set => image = value; }
    public List<string> Genre { get => genre; set => genre = value; }
    public string Content_rating { get => content_rating; set => content_rating = value; }
    public  List<IMDB_Entry> Actors { get => actors; set => actors = value; }
    public List<IMDB_Person> Directors { get => directors; set => directors = value; }
    public List<IMDB_Person> Creators { get => creators; set => creators = value; }
    public string Description { get => description; set => description = value; }
    public string Date { get => Date1; set => Date1 = value; }
    public string Date1 { get => date; set => date = value; }
    public List<string> Keywords { get => keywords; set => keywords = value; }
    public IMDB_Rating Rating { get => rating; set => rating = value; }
    public string Duration { get => duration; set => duration = value; }

还有两个类名为 IMDB_Rating 和 IMDB_Person,它们的代码如下:

public class IMDB_Person
{
    private string url;
    private string name;

    public string Name { get => name; set => name = value; }
    public string Url { get => url; set => url = value; }
}
public class IMDB_Rating
{
    public long Rating_count { get; set; }
    public decimal Best_Rating { get; set; }
    public decimal Worst_Rating { get; set; }
    public decimal Average_Rating { get; set; }
}

在我的应用程序中,我使用 HTML Agility 包来获取包含 JSON 格式的所有必要数据的字符串,如下所示:JSON

如何将 JSON 字符串中的数据获取到我的类中,我已经通过使用 if 语句并替换字符来逐行尝试,但它不会t really work and its 绝对不是一个优雅的解决方案。我对 json 很陌生,我用谷歌搜索了一下,但真的不知道该怎么做。提前致谢。

【问题讨论】:

  • 你需要一个 JSON 解析器,nuget 它。或者自己写。

标签: c# json parsing web-scraping imdb


【解决方案1】:

我会使用 newtonsoft.json 将 json 动态解析为字典。然后访问数据很容易。这里的例子。 https://www.newtonsoft.com/json/help/html/Introduction.htm

您还可以使用 JavaScript 序列化程序来解析 json。这里的例子https://www.codementor.io/andrewbuchan/how-to-parse-json-into-a-c-object-4ui1o0bx8

希望对您有所帮助。如果您仍然卡住,请告诉我,我很乐意提供进一步帮助。您也可以在 Twitter 上直接与我联系以寻求帮助。 https://twitter.com/NickCGamb

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 2019-02-16
    • 2017-06-01
    • 2021-09-02
    • 1970-01-01
    相关资源
    最近更新 更多