[英]Serialize empty object instead of null in Newtonsoft.JSON
這困擾了我一段時間。 我有 model:
public class Main
{
public Header header { get; set; }
public Response response { get; set; }
}
public class Response
{
public string projectId { get; set; }
public string designBriefId { get; set; }
public MDT mdt { get; set; }
public List<ReferenceMDT> referenceMDT { get; set; }
public List<ProductList> ProductList { get; set; }
}
public class MDT
{
[Key]
public string mdtAssetId { get; set; }
public bool isMDTDownloaded { get; set; }
public bool isNamingConventionCorrect { get; set; }
}
每當我將此 object 序列化為 JSON 時,使用:
Newtonsoft.Json
然后我變得無效(來自我正在處理的 API POV)JSON 轉換為空/空 object:
{
"header": "unimportant",
"response": {
"projectId": "Prj_02022022_2",
"designBriefId": "DB_02022022_4",
"mdt": null,
"referenceMDT": [],
"ProductList": []
}
}
重點是我想序列化為 output:
"mdt": {}
代替:
"mdt": null
所以問題是我如何將這個值“標記”為空 object 而不是 null 或者如何將其轉換為空 object? 正如我所提到的,它困擾了我一段時間,我不知道如何解決這個問題。 我試圖改變整個問題並將其更改為被忽略
JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}
但問題是 API 的另一邊必須收到空的 object,並且 null 或缺少 ZA8CFDE6331BD49EB2AC96F891 被視為錯誤。
As you can see in MDT model, there are mostly bool properties, so whenever I generate object as new() and Ignoring null values it fills all bools with false, generating me an object which is also considered error:
"mdt": {
"mdtAssetId": null,
"isMDTDownloaded": false,
"isNamingConventionCorrect": false,
"isFolderStructureProvidedByAgencyCorrect": false,
"heroImageGuidelinesAvailable": false,
"allImagesAvailable": false,
"isDesignTargetLocked": false,
"isPackagingGuidelinesAvailable": false,
"isRegulatoryGuidelinesAvailable": false,
"mdtResponse": null,
"pmaCommentsforMDT": null
}
我將非常感謝任何幫助甚至信息,這是不可能的,但如果空和 null object 之間存在差異,我認為它是可以解決的,但我太笨了,無法弄清楚。
TL;DR: I've got object and whenever I'm trying to serialize it to JSON, it's either returning me null, or object with bool values filled as "false", which both are error and I need empty object generated.
為了避免錯誤,只需將 bool 更改為 bool?
public class MDT
{
[Key]
public string mdtAssetId { get; set; }
public bool? isMDTDownloaded { get; set; }
public bool? isNamingConventionCorrect { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.