C#忽略为空的属性 [英] c# ignore properties that are null

查看:254
本文介绍了C#忽略为空的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Framewrok 4.5进行C# Web Api应用程序

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

该方法检索 class 定义为

public class BGBAResultadoOperacion
    {

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

我不需要检索那些 NULL 。因此,我定义了Descripcion属性,例如

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

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

由于无法从类中删除属性,因此将该类转换为Json

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

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

其中响应​​是 BGBAResultadoOperacion 类的实例。

Where response is an instance of BGBAResultadoOperacion class.

但是Json生成了 Descripcion: null

我不能使用 Json.Net ,因为我正在使用Framework.4.5。

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

如何我可以检索避免属性为null的数据吗?

How can I retrieve data avoiding properties that are null?

谢谢

推荐答案

使用Newtonsoft.Json进行序列化时,请使用NullValueHandling选项。

Use the NullValueHandling option when Serializing using Newtonsoft.Json.

从文档中获取

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

这篇关于C#忽略为空的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆