2024/06/18

[C#][WebAPI] Json.NET / System.Text.Json 序列化物件中忽略 null 值的屬性

近期遊走在 ASP.NET MVC 5 / Web API 2 以及 ASP.NET Core MVC (.NET) 的專案中

對於由 API 讀取進來的物件在 .NET Framework 與 .NET 下處理的方式不同, 需要記錄一下以便日後翻查

場景需求

使用場景是把接收進來的物件內容轉換做一個清洗,只要從 Web API 接進來的物件屬性值為 null 的都不保留

例如: 有一個 Log 物件如下

var log = new Log {
  Timestamp = "2024-06-16T09:22:01.5120098Z",
  Level = "Information",
  Message = "This is test message",
  Exception = null
};

那麼經過清洗過後的字串內容就不會包含 Exception 空值的屬性

{
  "Timestamp":"2024-06-16T09:22:01.5120098Z",
  "Level":"Information",
  "Message":"This is test message"
}

以下即是在 ASP.NET MVC 5 及 ASP.NET Core 不同環境的處理方式

環境 (ASP.NET MVC 5 + Web API 2)

  • .NET Framework 4.7.2+
  • Json.NET (Newtonsoft.Json) v13.x

方法 1: 在物件屬性加上 [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]

public class Log
{
    public DateTime Timestamp { get; set; }
    public string Level { get; set; }
    public string Message { get; set; }

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string Exception { get; set; }
}

方法 2: 在序列化物件時加上 JsonSerializerSettings 如下

var strJson = JsonConvert.SerializeObject(obj, 
    Newtonsoft.Json.Formatting.None, 
    new JsonSerializerSettings { 
        NullValueHandling = NullValueHandling.Ignore
    });

環境 (ASP.NET Core MVC)

  • .NET 6
  • System.Text.Json

在物件的屬性上加上 [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]

public class Log
{
    public DateTime Timestamp { get; set; }
    public string Level { get; set; }
    public string Message { get; set; }

    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    public string? Exception { get; set; }
}

References