我有一个或多或少看起来像这样的字段
{
"Photos" :
[
{
"file_id" : "Some value",
"type" : "Some certain value",
/*'Photo's specific fields*/
},
{
"file_id" : "Some value",
"type" : "Some certain value",
/*'Photo's specific fields*/
},
{
"file_id" : "Some value",
"type" : "Some certain value",
/*'Photo's specific fields*/
}
],
"Document" :
{
"file_id" : "Some value",
"type" : "Some certain value",
/*'Document's specific fields*/
},
"Video" :
{
"file_id" : "Some value",
"type" : "Some certain value",
/*'Video's specific fields*/
},
}
在此类中将整个JSON供应到该类别
public class APIResponse
{
[JsonProperty(PropertyName = "Photos")]
public List<APIFile> Photos;
[JsonProperty(PropertyName = "Document")]
public APIFile Document;
[JsonProperty(PropertyName = "Video")]
public APIFile Video;
}
其中 APIFile
是一个对每个json域的"目标类型"的类,看起来像是这样
public class APIFile
{
public enum FileMIME
{
// Some already specified enum values
}
[JsonProperty(PropertyName = "file_id")]
public string FileID;
[JsonProperty(PropertyName = "type")]
public string FileType;
[JsonIgnore()]
public FileMIME MIMEType;
}
您可以看到,JSON中的这三个字段共享了一些公共字段file_id
和type
,其中Photos
是某些类型的收集,也共享相同的公共字段。
问题是,我该如何对每个人进行应有的序列化,但是将MIMEType
字段设置为应序列化字段?最好不使用JsonConverter
或添加额外的类
例如,当它是必不可少的JSON字段Document
时,将创建APIResponse
对象中的字段Document
使用MIMEType
字段具有值MIMEType.Document
您可以将固定器与备用私有字段使用:
public enum FileMIME
{
Document,
Photos,
Video
}
public class APIResponse
{
private List<APIFile> _photos;
[JsonProperty(PropertyName = "Photos")]
public List<APIFile> Photos
{
get { return _photos; }
set { _photos = value;
foreach(var photo in _photos)
{
photo.MIMEType = FileMIME.Photos;
}
}
}
private APIFile _document;
[JsonProperty(PropertyName = "Document")]
public APIFile Document
{
get { return _document; }
set { _document = value; _document.MIMEType = FileMIME.Document; }
}
private APIFile _video;
[JsonProperty(PropertyName = "Video")]
public APIFile Video
{
get { return _video; }
set { _video = value; _video.MIMEType = FileMIME.Video; }
}
}
您可以使用 Dictionary<string, object>
而不是apifile类。然后,您可以在返回响应之前将filemime添加到每个字典中。