I can use the ExcludeDefaultValues to exclude json serializing of null values in strings. But I also want "" to be excluded. I do not have access to the model to set custom attributes. Is there a way to create a kind of override in the string serializer?
In Newtonsoft I can do:
No actually. It is not for 1 specific model, but for every object that I want to serialize. So I need a more generic approach that works for every object given where a string is used (hierarchical)
Out of pure coincidence, I was just looking for something to do this for me on only my inbound JSON, but I believe mythz solution here might be what you need? Or a starter, at least?
There’s no JS configuration that lets you configure this behavior, the only 2 generic solutions I can think of is similar to @daleholborow link of registering a Response Filter that uses reflection to generically go through each property and replace each empty string with null.
The other solution is to add a ShouldSerialize() API on POCOs you want this behavior on to ignore any string properties with null or empty values, e.g:
public class Poco {
public bool? ShouldSerialize(string name) => this.IgnoreEmptyStrings(name);
}
public static class MyExt
{
public static bool? IgnoreEmptyStrings<T>(this T obj, string name)
{
var accessor = TypeProperties.Get(typeof(T)).GetAccessor(name);
return accessor?.PropertyInfo.PropertyType == typeof(string)
? !string.IsNullOrEmpty((string)accessor.PublicGetter(this))
: (bool?)null;
}
}