【问题标题】:c# ignore properties that are nullc#忽略为空的属性
【发布时间】:2019-02-06 23:54:04
【问题描述】:

我正在使用 Framewrok 4.5 编写 C# Web Api Application

该方法检索像这样定义的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 的属性。出于这个原因,我定义了描述属性,如

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

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

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

其中 response 是 BGBAResultadoOperacion 类的实例。

但是生成的 Json 说 "Descripcion":"null"

我无法使用Json.Net,因为我使用的是 Framework.4.5。

如何检索数据以避免属性为空?

谢谢

【问题讨论】:

  • "我无法使用 Json.Net,因为我使用的是 Framework.4.5。" - Json.NET 下降到 .NET Framework 2.0;是什么让你认为你不能使用它?另外:DataContractJsonSerializer 在这里工作吗? 可以完成这项工作吗? (虽然它是 Json.NET 的一个可怜的表亲)
  • 我通过 Nuget 添加 Json.Net 并说它无法添加,因为我使用的是框架 4.5,我没有使用 DataContractJsonSerializer,我必须检查一下。谢谢
  • "已成功将 'Newtonsoft.Json 12.0.1' 安装到 ConsoleApp35" - 在这里可以正常工作;您在使用旧的 IDE/工具吗?
  • 好的,我已经安装了Newtonsoft.Json 12.0.1,我已经尝试安装Json.Net,那是错误...安装后,你能告诉我如何避免空属性?谢谢!!

标签: c# json class properties


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    相关资源
    最近更新 更多