简体   繁体   中英

c# ignore properties that are null

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

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
// }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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