【发布时间】:2019-01-16 14:52:36
【问题描述】:
将DefaultValue 应用于每个字符串属性。
上下文:
以下类是自动生成的。并且编辑它们以添加这些属性是一种负担。由于生成的类很大,并且生成的代码有很多现有的属性等。我制作了一个程序来打开 CS 文件并使用一些正则表达式来添加属性。但仍需维护程序以匹配生成的文件名。
使用 Json.Net,为了在序列化结果中隐藏空字符串,我必须使用 [DefaultValue("")] 定义这些字符串的默认值。
在下面的例子中,我们有一些类和嵌套类。 目的是在序列化 Foo 项目时隐藏 Bar 中的空字符串。
public class Foo
{
public int Prop1;
[DefaultValue("")]
public string Prop2;
public int? Prop3;
public Bar Prop4;
public Bar[] Prop5;
};
public class Bar
{
public int Prop1;
public string Prop2;
public int? Prop3;
};
public void NullOrEmptyStringTerminator()
{
var bar = new Bar { Prop1 = 0, Prop2 = "", Prop3 = 0 };
var bar2 = new Bar { Prop1 = 0, Prop3 = 0 };
var inputs = new[] {
new Foo{ Prop1= 1, Prop2="", Prop4= bar, Prop5 = new []{bar} },
new Foo{ Prop1= 1, Prop4= bar, Prop5 = new []{bar2} },
};
var jsonResults =
inputs
.Select(x =>
new
{
Item = x,
NormalSerialisation =
JsonConvert.SerializeObject(
x,
Formatting.Indented,
new JsonSerializerSettings { }
),
CustomSerialisation =
JsonConvert.SerializeObject(
x,
Formatting.Indented,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore,
})
}
).ToList();
}
测试用例:
class Foo :
int Prop1 -> Real value 1
string Prop2 -> No value either "" or null
int? Prop3 -> No value null
Bar Prop4 -> Real value Bar
Bar[] Prop5 -> Real value Bar[]
class Bar :
int Prop1 -> No value 0.
string Prop2 -> Same test than Foo.Prop2
int? Prop3 -> Real value 0; Not null
预期结果适用于两个输入 Json。
{
"Prop1": 1,
"Prop4": {
"Prop3": 0
},
"Prop5": [
{
"Prop3": 0
}
]
}
【问题讨论】:
-
DefaultValueHandling、NullValueHandling和[DefaultValue("")],已出现在此问题中。我将使用 C# fiddle 和 CustomSerialisation 的打印进行更新。当我使用 PC 时 -
是的,您已经在使用
DefaultValueHandling,但是您忘记在Bar中将DefaultValueAttribute添加到Prop2。那么只有Prop1和Prop3(当设置为0时)。Foo正在工作,对吧? -
如果你不能修改
Bar,那么你必须write custom converter for properties containingBar。 -
没有。别忘了。我有很多课。并且需要某种概括