Reputation: 4084
When I seralise an object, for some string properties, I would like to output empty string other than ignore or output null.
According to newton's doc, I could do this:
public class Data
{
public int ProductId { get; set; }
[DefaultValue("")]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Include)]
public string LargeData { get; set; }
}
However, in my test case, it still output null
Data D1 = new Data()
{
ProductId = 1
};
var b = JsonConvert.SerializeObject(D1);
The output is {"ProductId":1,"LargeData":null}
. Am I doing something wrong?
Upvotes: 2
Views: 369
Reputation: 1502016
Looking at DefaultValueHandling
it doesn't look like there's any way of doing what you want.
The default value attribute is only used when deserializing, if the property isn't specified in the JSON. The ignore / include choices are the ones which are relevant when serializing, and those don't affect the value that's serialized - just whether or not it should be serialized.
Unless you've got code which actually sets the value to null, the simplest option would be to make the property default to "" from a .NET perspective:
public class Data
{
public int ProductId { get; set; }
public string LargeData { get; set; } = "";
}
Upvotes: 4