Exclude null fields while serialization using Utf8Json library?

喜你入骨 提交于 2021-02-10 06:48:53

问题


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?


回答1:


Use resolver:

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


来源:https://stackoverflow.com/questions/64883796/exclude-null-fields-while-serialization-using-utf8json-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!