【发布时间】:2020-08-21 18:03:54
【问题描述】:
我编写了一个应用程序,通过抓取电影页面源来获取 IMDb 电影信息。页面源中的一些电影数据是 JSON 格式,电影模式来自“Schema.org”。
{
"@context": "http://schema.org",
"@type": "Movie",
"url": "/title/tt7131622/",
"name": "Once Upon a Time... in Hollywood",
"genre": [
"Comedy",
"Drama"
],
"actor": [
{
"@type": "Person",
"url": "/name/nm0000138/",
"name": "Leonardo DiCaprio"
},
{
"@type": "Person",
"url": "/name/nm0000093/",
"name": "Brad Pitt"
},
{
"@type": "Person",
"url": "/name/nm3053338/",
"name": "Margot Robbie"
},
{
"@type": "Person",
"url": "/name/nm0386472/",
"name": "Emile Hirsch"
}
],
"director": {
"@type": "Person",
"url": "/name/nm0000233/",
"name": "Quentin Tarantino"
},
"creator": [
{
"@type": "Person",
"url": "/name/nm0000233/",
"name": "Quentin Tarantino"
},
{
"@type": "Organization",
"url": "/company/co0050868/"
},
{
"@type": "Organization",
"url": "/company/co0452101/"
},
{
"@type": "Organization",
"url": "/company/co0159772/"
}
}
我创建了一个“电影”类来反序列化 JSON 对象。有一个名为“Director”的属性Person 类。
internal class ImdbJsonMovie
{
public string Url { get; set; }
public string Name { get; set; }
public string Image { get; set; }
public List<string> Genre { get; set; }
public List<ImdbJsonPerson> Actor { get; set; }
public ImdbJsonPerson Director { get; set; }
//public string[] Creator { get; set; }
}
没关系。但问题是有些电影,比如《黑客帝国》,导演不止一位。
{
"@context": "http://schema.org",
"@type": "Movie",
"url": "/title/tt0133093/",
"name": "The Matrix",
"genre": [
"Action",
"Sci-Fi"
],
"actor": [
{
"@type": "Person",
"url": "/name/nm0000206/",
"name": "Keanu Reeves"
},
{
"@type": "Person",
"url": "/name/nm0000401/",
"name": "Laurence Fishburne"
},
{
"@type": "Person",
"url": "/name/nm0005251/",
"name": "Carrie-Anne Moss"
},
{
"@type": "Person",
"url": "/name/nm0915989/",
"name": "Hugo Weaving"
}
],
"director": [
{
"@type": "Person",
"url": "/name/nm0905154/",
"name": "Lana Wachowski"
},
{
"@type": "Person",
"url": "/name/nm0905152/",
"name": "Lilly Wachowski"
}
],
"creator": [
{
"@type": "Person",
"url": "/name/nm0905152/",
"name": "Lilly Wachowski"
},
{
"@type": "Person",
"url": "/name/nm0905154/",
"name": "Lana Wachowski"
},
{
"@type": "Organization",
"url": "/company/co0002663/"
},
{
"@type": "Organization",
"url": "/company/co0108864/"
},
{
"@type": "Organization",
"url": "/company/co0060075/"
},
{
"@type": "Organization",
"url": "/company/co0019968/"
},
{
"@type": "Organization",
"url": "/company/co0070636/"
}
}
所以一定是List<Person>。
internal class ImdbJsonMovie
{
public string Url { get; set; }
public string Name { get; set; }
public string Image { get; set; }
public List<string> Genre { get; set; }
public List<ImdbJsonPerson> Actor { get; set; }
public List<ImdbJsonPerson> Director { get; set; }
//public string[] Creator { get; set; }
}
另一个问题是如何反序列化由 Person 类和 Organization 类创建的 creator 属性。
所以问题是“如何反序列化这个复杂的 JSON 对象?”
谢谢
【问题讨论】:
-
我猜,你应该为这些属性编写自己的转换器
标签: c# json deserialization imdb