方法:
/// <summary> /// 递归剔除JObject中值为null的字段 /// </summary> static void RemoveNullProperties(JToken token) { if (token.Type == JTokenType.Object) { var jObj = (JObject)token; var propertiesToRemove = jObj.Properties() .Where(p => p.Value == null || p.Value.Type == JTokenType.Null || string.IsNullOrEmpty((string)p.Value)|| (p.Value.Type == JTokenType.String && string.IsNullOrWhiteSpace((string)p.Value)) || (p.Value.Type == JTokenType.Array && !p.Value.HasValues)) .ToList(); foreach (var prop in propertiesToRemove) prop.Remove(); foreach (var child in jObj.Children()) { if (child.Children().Count() > 0) { RemoveNullProperties(child); } } } else if (token.Type == JTokenType.Property) { if (token.Children().Count() > 0) { var childs = token.Children().Where(p => p == null || p.Type == JTokenType.Null || string.IsNullOrEmpty((string)p) || (p.Type == JTokenType.String && string.IsNullOrWhiteSpace((string)p)) || (p.Type == JTokenType.Array && !p.HasValues)) .ToList(); foreach (var prop in childs) prop.Remove(); foreach (var child in token.Children()) { if (child.Children().Count() > 0) { RemoveNullProperties(child); } } } } else if (token.Type == JTokenType.Array) { var jArray = (JArray)token; // 清理数组内部的 null / "" for (int i = jArray.Count - 1; i >= 0; i--) { var item = jArray[i]; if (item.Type == JTokenType.Null || (item.Type == JTokenType.String && string.IsNullOrWhiteSpace((string)item))) { jArray.RemoveAt(i); } } // 递归数组内对象/子数组 foreach (var child in jArray) RemoveNullProperties(child); // 如果数组最后变空,也删除 if (!jArray.HasValues) { if (jArray.Parent is JProperty prop) prop.Remove(); } } }调用:
object reqHeader = new { transTime = "20260421171327", reqId = "123456", test = null }; JObject reqHeaderJobject = JObject.FromObject(reqHeader); RemoveNullProperties(reqHeaderJobject); //剔除后reqHeaderJobject为{"transTime":"20260421171327","reqId":"123456"}