如果在Newtonsoft json中为null,如何跳过序列化对象?

时间:2016-03-09 05:34:04

标签: c# json serialization null json.net

我正在使用Json.net序列化程序来序列化对象。它工作正常。现在根据我的要求,我使用JsonDotNetCustomContractResolvers从对象中排除属性。但是对于下面的show对象,我需要排除所有属性

$this->User_model->makeAdmin($cleanPost);

当我这样做时,我得到了我想要的结果。结果如下图所示。

enter image description here 这里排除了属性,但是null对象仍然是序列化的。有没有办法跳过newtonsoft JSON中null对象的序列化。

1 个答案:

答案 0 :(得分:1)

我写了一个快速测试应用程序,向您展示您可能想要尝试的内容。 Json.Net有一个很好的属性,JsonObject,加上设置MemberSerialization.OptIn。这意味着只有JsonProperty的属性才会被序列化。

public class JsonNet_35883686
{
    [JsonObject(MemberSerialization.OptIn)]
    public class CreditCard
    {
        [JsonProperty]
        public int Id { get; set; }
        public int CustomerId { get; set; }
    }

    public static void Run()
    {
        var cc = new CreditCard {Id = 1, CustomerId = 123};
        var json = JsonConvert.SerializeObject(cc);
        Console.WriteLine(json);

        cc = null;
        json = JsonConvert.SerializeObject(cc);
        Console.WriteLine(json);
    }
}

run的输出是(Id被序列化的原因是因为我使用了JsonProperty

{"Id":1}
null

希望这有帮助。