简体   繁体   English

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

[英]How to skip serializing an object if it null in Newtonsoft json?

I am using Json.net serializer for serializing objects.It is working perfectly.Now as per my requirement, I have used JsonDotNetCustomContractResolvers to exclude properties from an object.But for the below show object, I need to exclude all it properties. 我正在使用Json.net序列化程序对对象进行序列化。它工作正常。现在根据我的要求,我已经使用JsonDotNetCustomContractResolvers从对象中排除属性。但是对于以下show对象,我需要排除其所有属性。

Partial Public Class CreditCard
    <Key> _
    Public Property ID As Integer
    Public Property CustomerID As Integer
    Public Property CardType As String
    Public Property Last4Digit As String
    Public Property ExpiryDate As String
    Public Property Token As String
    Public Property IsPrimary As Boolean
End Class

And when I do that I get the result as I wanted. 当我这样做时,我会得到想要的结果。 Result Shown in below image. 结果如下图所示。

在此处输入图片说明 Here the properties are excluded, but the null object is still serialized.Is there any way to skip the serialization of null objects in newtonsoft JSON. 这里的属性被排除在外,但是null对象仍然是序列化的。有什么方法可以跳过newtonsoft JSON中null对象的序列化。

I wrote a quick test app to show you what you might want to try. 我写了一个快速测试应用程序,向您展示了您可能想尝试的内容。 There is a great attribute for Json.Net, JsonObject , coupled with the setting MemberSerialization.OptIn . Json.Net, JsonObject有一个很棒的属性,再加上设置MemberSerialization.OptIn This means that only properties with JsonProperty will be serialized. 这意味着只有带有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);
    }
}

The output of run is (the reason Id is serialized is because I used JsonProperty run的输出是(将Id序列化的原因是因为我使用了JsonProperty

{"Id":1}
null

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM