使用标准.NET Xml Serializer时,有什么办法可以隐藏所有空值吗?以下是我班级输出的一个例子.如果它们被设置为null,我不想输出可空整数.
当前的Xml输出:
<?xml version="1.0" encoding="utf-8"?>
<myClass>
<myNullableInt p2:nil="true" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance" />
<myOtherInt>-1</myOtherInt>
</myClass>
Run Code Online (Sandbox Code Playgroud)
我想要的是:
<?xml version="1.0" encoding="utf-8"?>
<myClass>
<myOtherInt>-1</myOtherInt>
</myClass>
Run Code Online (Sandbox Code Playgroud) 在.NET世界中,当谈到对象序列化时,它通常用于在运行时检查对象的字段和属性.对此作业使用反射通常很慢,并且在处理大量对象时是不合需要的.另一种方法是使用IL发射或构建表达树,这些表现树相对于反射提供显着的性能增益.而后者是处理序列化时最现代化的库.但是,在运行时构建和发送IL需要花费时间,并且只有在将此信息缓存并重用于相同类型的对象时才会回收投资.
当使用Json.NET时,我不清楚使用上述哪种方法,如果确实使用了后者,是否使用了缓存.
例如,当我这样做时:
JsonConvert.SerializeObject(new Foo { value = 1 });
Run Code Online (Sandbox Code Playgroud)
Json.NET是否构建了Foo的成员访问信息并缓存以便以后重用它?
虽然我发现了许多方法来反序列化特定属性,同时阻止它们序列化,但我正在寻找相反的行为.
我发现有很多问题要求反过来:
我可以指示Json.NET反序列化,但不能序列化特定属性吗?
JSON.Net - 仅在序列化时使用JsonIgnoreAttribute(但在反序列化时不使用)
如何序列化特定属性,但阻止它反序列化回POCO?是否有可用于装饰特定属性的属性?
基本上我正在寻找与反序列化的ShouldSerialize*方法相当的方法.
我知道我可以写一个自定义转换器,但这似乎有点矫枉过正.
编辑:
这是一个更多的背景.这背后的原因是我的班级看起来像:
public class Address : IAddress
{
/// <summary>
/// Gets or sets the two character country code
/// </summary>
[JsonProperty("countryCode")]
[Required]
public string CountryCode { get; set; }
/// <summary>
/// Gets or sets the country code, and province or state code delimited by a vertical pipe: <c>US|MI</c>
/// </summary>
[JsonProperty("countryProvinceState")]
public string CountryProvinceState
{
get
{
return string.Format("{0}|{1}", this.CountryCode, this.ProvinceState);
}
set
{
if (!string.IsNullOrWhiteSpace(value) && value.Contains("|")) …Run Code Online (Sandbox Code Playgroud)