Parth Patel
Parth Patel

Reputation: 3997

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.

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.

enter image description here 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.

Upvotes: 1

Views: 3057

Answers (2)

Kolappan N
Kolappan N

Reputation: 4011

You can use the NullValueHandling setting in Newtonsoft.Json to ignore objects or keys with null values.

string jsonIgnoreNullValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore
});

Ref: NullValueHandling Documentation

Upvotes: 1

sQuir3l
sQuir3l

Reputation: 1383

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. This means that only properties with JsonProperty will be serialized.

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

{"Id":1}
null

Hope this helps.

Upvotes: 1

Related Questions