【发布时间】:2020-12-16 13:30:30
【问题描述】:
我有一个如下结构的 JSON 文件。
{
title: {
title: "",
episode_title: ""
},
series: {
season: "",
episode: ""
}
content_description: {
???
}
}
,其中 content_description 可能具有以下格式之一:
content_description: {
language: "",
short_synapsis: "",
medium_synopsis: "",
long_synopsis: "",
oneliner: ""
}
OR
content_description: {
text: "",
category: "",
level: "",
source: ""
}
我想使用 Newtonsoft Json.NET JsonConvert.DeserializeObject(string value) 方法将其序列化为 C# 模型。到目前为止,我已经创建了以下 content_description 模型:
public class ContentDescriptions
{
public string language { get; set; }
public string short_synopsis { get; set; }
public string medium_synopsis { get; set; }
public string long_synopsis { get; set; }
public string short_season_synopsis { get; set; }
public string medium_season_synopsis { get; set; }
public string long_season_synopsis { get; set; }
public string short_episode_synopsis { get; set; }
public string medium_episode_synopsis { get; set; }
public string long_episode_synopsis { get; set; }
public string oneliner { get; set; }
public string text { get; set; }
public string category { get; set; }
public string level { get; set; }
public string source { get; set; }
}
这可行,但是有没有办法将具有一个名称的元素序列化为两个模型之一,具体取决于其结构?例如,在我的根模型中有两个 content_description 模型字段并填充其中一个而将另一个留空?
【问题讨论】:
-
不能将 JSON 序列化为任何东西,因为 JSON 本身就是序列化的结果。不清楚,你的确切问题是什么。您有没有按预期工作的代码示例?
-
尝试将结果转换为匿名对象或动态,然后查找在另一个模型上不重复的字段之一,然后决定选择哪个模型进行转换。
-
@Aegonek 请也与我们分享您的 json 文件。另外请尝试与我们分享您是如何尝试解决此问题的以及您在哪里卡住了。