【发布时间】:2021-12-13 06:33:49
【问题描述】:
我正在尝试在 c# 对象中实现 json 结构,并且我正在尝试了解如何根据类型使用正确的对象。例如:
public class RootObject
{
public string name { get; set; }
public Content content { get; set; }
}
public class Content
{
public string id{ get; set; }
public string type { get; set; }
public Dictionary<string, Item> child { get; set; }
}
public class Item
{
public string id { get; set; }
public string type { get; set; }
public List<string> model { get; set;}
public string[] color {get; set;}
}
请注意,这只是一个示例,每个对象都有更多属性。如果 Json 包含 type = "Boy" 我如何生成男孩对象。
示例 JSON:
string json = @"
{
'name': 'Object 1',
'content': {
'body': {
'id': 'body',
'type': 'Body'
},
'style': {
'id': 'style',
'type': 'Style'
},
'DynamicName-123': {
'id': 'DynamicName-123',
'type': 'Row'
'model': {},
'colors': []
},
'DynamicName-434': {
'id': 'DynamicName-434',
'type': 'Column'
'model': {},
'colors': []
},
'DynamicName-223': {
'id': 'DynamicName-223',
'type': 'Item'
'model': {},
'colors': []
}
}
}";
【问题讨论】:
-
您可以更改生成的 json 以包含类型,还是您正在接收的数据?如果您无法更改它,我认为您可能必须实现自己的自定义 JsonConverter 并根据属性覆盖读取方法
-
是的,json 包括 json 中的类型以及静态的 Id。 @Icepickle
-
请阅读How to Ask 并展示您的尝试。另外,创建一个minimal reproducible example,包括一些示例 JSON。参见例如How to deserialize a JSON array containing different data types to a single object。您可能需要一个自定义的 JsonConverter,它根据 JSON 中的
type字符串实例化适当的类型。 -
你有机会分享一个 json 样本吗?
-
能否请您展示您的 json 以清楚了解您是否尝试这样做?