AndyP
AndyP

Reputation: 607

Exclude null fields while serialization using Utf8Json library?

Is there any way to ignore null fields while serializing POCO to JSON string using Utf8Json library?

I have a ToString method in my below class which I am using externally so I wanted to see if there is any way to exclude null fields while doing serialization? Basically I don't want null fields in my json string after serialization. I am using Uft8Json library here.

public class Process
{
    public Process() { }

    [DataMember(Name = "lang_code")]
    public string LCode { get; set; }

    [DataMember(Name = "data_currency")]
    public string Currency { get; set; }

    [DataMember(Name = "country_code")]
    public string CCode { get; set; }

    public override string ToString()
    {
        return Utf8Json.JsonSerializer.ToJsonString(this);
    }
}

I tried reading the docs but couldn't find it. Is there any way to do this using Utf8Json library?

Upvotes: 2

Views: 1263

Answers (1)

Alexander Petrov
Alexander Petrov

Reputation: 14231

Use resolver:

return Utf8Json.JsonSerializer.ToJsonString(this, 
    Utf8Json.Resolvers.StandardResolver.ExcludeNull);

Upvotes: 2

Related Questions