Dot-Net
JSON序列化 - 刪除空鍵
我正在使用 .Net Web API 技術創建一個 HTTP 服務,我創建了一些 DTO 類,當只需要某個數據子集時,我計劃只用該數據填充 DTO 以最小化數據量轉移。
有沒有辦法讓 JSON 序列化器忽略那些為空的數據成員?我意識到有
$$ JsonIgnore $$和$$ ScriptIgnore $$將忽略特定成員的屬性,但我只想在它們為空或為空時忽略它們。 $$ Edit $$ 感謝下面的LB
我將以下內容添加到 WebApiConfig.cs 以在 Web API 中啟用此功能:
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
Json.Net 對此有一個設置
var str = JsonConvert.SerializeObject(obj, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });