本文將為大家介紹在 C# 中處理 JSON null 不顯示的解決方法。
一、null 不顯示的問題
在使用 C# 進行 JSON 數據處理的時候,經常會遇到 null 值不顯示的情況。當一個 JSON 對象的某個鍵對應的值為 null 時,在轉換為 C# 對象後,該屬性將會被忽略。
class Example { public string Name {get; set;} public int? Age {get; set;} } // JSON 數據 { "Name":"Tom", "Age": null } // 在使用 C# 進行轉換後 Example example = JsonConvert.DeserializeObject<Example>(json); example.Name == "Tom"; example.Age == null; // null 不顯示
在上述示例中,當 JSON 串中 Age 字段為 null 時,在反序列化後,該值被忽略。
二、解決方法
1. 使用 JToken 處理 null 值
如果您需要讓 null 值在轉換後保留在 C# 對象中,則可以使用 JToken 處理 null 值。 JToken 表示一個 JSON 序列化器可以處理的任意 JSON 令牌。它可以表示 JSON 實體、數組、原始值以及 null。
// JSON 字符串 { "Name":"Tom", "Age": null } // 處理 null 值 var jObject = JObject.Parse(json); var example = new Example(); var age = jObject.SelectToken("Age"); example.Age = (int?) age;
在上述示例中,使用 JObject.Parse 方法將 JSON 串轉換為 JObject,然後使用 SelectToken 方法選擇 Age 字段並將其轉換為 int? 類型,以此來保留 null 值。
2. 使用 DefaultValueHandling.Ignore 處理 null 值
另外,可以使用 DefaultValueHandling.Ignore 將 null 值忽略,這樣被忽略的值會保留在 JSON 格式中。
class Example { public string Name { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? Age { get; set; } } // JSON 數據 { "Name":"Tom", "Age": null } // 使用 DefaultValueHandling.Ignore 屬性 var example = JsonConvert.DeserializeObject<Example>(json); example.Name == "Tom"; example.Age == null; // null 值保留
在上述示例中,使用屬性 DefaultValueHandling.Ignore 將 null 值忽略,以此來保留忽略的值。
三、總結
在 C# 中,處理 JSON null 值不顯示的問題,可以使用 JToken 處理 null 值,也可以使用 DefaultValueHandling.Ignore 屬性將 null 值忽略。這些處理方式,能夠讓您更好地使用 C# 處理 JSON 數據。
原創文章,作者:YUPEB,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/373746.html