在指定的可为空的字段上增加特性“[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]”即可;
class Program { static void Main(string[] args) { TestMan test = new TestMan(); test.Name = "Name"; string end = JsonConvert.SerializeObject(test); Console.WriteLine(end); Console.ReadKey(); } } public class TestMan { [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string Name { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public int? Age { get; set; } }
执行效果如下(序列化的结果中,没有Age字段的相关信息):