我有一个JSON,其中的字段或多或少看起来像这样
{
"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
时,将创建Document
对象中的字段APIResponse
其中MIMEType
字段的值为MIMEType.Document
答案 0 :(得分:0)
您可以将setter用于支持私有字段:
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; }
}
}
答案 1 :(得分:0)
您可以使用Dictionary<string, object>
代替APIFile类。然后,可以在返回响应之前将FileMIME添加到每个字典。