c# ignore properties that are null

落爺英雄遲暮 提交于 2019-12-24 10:23:16

问题


I am doing an C# Web Api Application using Framewrok 4.5

The method retrieve a class defined like this

public class BGBAResultadoOperacion
    {

        public string Codigo { get; set; }
        public string Severidad { get; set; }
        [DataMember(Name = "Descripcion", EmitDefaultValue = false)]
        public string Descripcion { get; set; }
    }

I need to NOT retrieve those Properties that are NULL. For that reason I defined Descripcion property like

[DataMember(Name = "Descripcion", EmitDefaultValue = false)]

As I can not remove a property from a class, I convert the class to Json

 var json = new JavaScriptSerializer().Serialize(response);

Where response is an instance of BGBAResultadoOperacion class.

But the Json generated say "Descripcion":"null"

I can not use Json.Net because I am using Framework.4.5.

How can I retrieve data avoiding properties that are null?

Thanks


回答1:


Use the NullValueHandling option when Serializing using Newtonsoft.Json.

From the documentation:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Person Partner { get; set; }
    public decimal? Salary { get; set; }
}

Person person = new Person
{
    Name = "Nigal Newborn",
    Age = 1
};

string jsonIncludeNullValues = JsonConvert.SerializeObject(person, Formatting.Indented);

Console.WriteLine(jsonIncludeNullValues);
// {
//   "Name": "Nigal Newborn",
//   "Age": 1,
//   "Partner": null,
//   "Salary": null
// }

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

Console.WriteLine(jsonIgnoreNullValues);
// {
//   "Name": "Nigal Newborn",
//   "Age": 1
// }


来源:https://stackoverflow.com/questions/54556896/c-sharp-ignore-properties-that-are-null

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