[英]c# ignore properties that are null
I am doing an C# Web Api Application
using Framewrok 4.5 我正在使用Framewrok 4.5制作C#
Web Api Application
The method retrieve a class
defined like this 该方法检索一个
class
这样定义
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
. 我不需要检索那些为
NULL
属性。 For that reason I defined Descripcion property like 因此,我定义了Descripcion属性,例如
[DataMember(Name = "Descripcion", EmitDefaultValue = false)]
As I can not remove a property from a class, I convert the class to Json 由于无法从类中删除属性,因此将类转换为Json
var json = new JavaScriptSerializer().Serialize(response);
Where response is an instance of BGBAResultadoOperacion
class. 其中response是
BGBAResultadoOperacion
类的实例。
But the Json generated say "Descripcion":"null"
但是Json产生了说
"Descripcion":"null"
I can not use Json.Net
because I am using Framework.4.5. 我无法使用
Json.Net
因为我正在使用Framework.4.5。
How can I retrieve data avoiding properties that are null? 如何检索数据以避免出现null属性?
Thanks 谢谢
Use the NullValueHandling option when Serializing using Newtonsoft.Json. 使用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
// }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.