I'm trying to serialize my struct so that the strings that didn't get a value get their default value "" instead of null
[JsonProperty(PropertyName = "myProperty", DefaultValueHandling = DefaultValueHandling.Populate)]
[DefaultValue("")]
public string MyProperty{ get; set; }
My result in the Json string:
"myProperty": null,
what i want
"myProperty": "",
I also tried creating a converter without any effect, the can Convert and WriteJson functions aren't even firing for some reason:
[JsonProperty(PropertyName = "myProperty")]
[JsonConverter(typeof(NullToEmptyStringConverter))]
public string MyProperty{ get; set; }
class NullToEmptyStringConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(object[]);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
writer.WriteValue("");
}
}
This isnt helping either Json.Net How to deserialize null as empty string?
DefaultValue
attribute is not to give the property a default value. It is only meant as a signal to serialization that if the property has that value at the time of serialization, it doesn't need to be serialized since it will get that value by default. If you don't actually give that property that value by default then you are in fact abusing that attribute. – Neptune