Apply DefaultValue
to every string properties.
Context:
The Following class are automatically generated. And Editing them to add those property is a burden. As generated class is quite big, and generated code has a lot of existing property etc. I made a program that open the CS file and use some regex to add the property. but still have to maintain the programme to match the generated file name.
With Json.Net, in order to hide empty string in the serialisation result I have to define the default value of those string with [DefaultValue("")]
.
In the following exemple we have some class and nested class. The aim is to hide the empty string in Bar when serialising a Foo item.
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();
}
Test Case:
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
The expect result is for both of the input Json.
{
"Prop1": 1,
"Prop4": {
"Prop3": 0
},
"Prop5": [
{
"Prop3": 0
}
]
}