c# ignore properties that are null

2019-08-09 04:17发布

问题:

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