I'm using Newtonsoft's Json.NET 7.0.0.0 to serialize classes to JSON from C#:
class Foo
{
public string X;
public List<string> Y = new List<string>();
}
var json =
JsonConvert.SerializeObject(
new Foo(),
Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
The value of json
here is
{ "Y": [] }
but I would like it to be { }
if Y
is an empty list.
I couldn't find a satisfactory way to achieve this. Maybe with a custom contract resolver?
JsonSerializationException(String, String, Int32, Int32, Exception) Initializes a new instance of the JsonSerializationException class with a specified error message, JSON path, line number, line position, and a reference to the inner exception that is the cause of this exception.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
Json.NET has excellent support for serializing and deserializing collections of objects. To serialize a collection - a generic list, array, dictionary, or your own custom collection - simply call the serializer with the object you want to get JSON for.
If you're looking for a solution which can be used generically across different types and does not require any modification (attributes, etc), then the best solution that I can think if would be a custom DefaultContractResolver
class. It would use reflection to determine if any IEnumerable
s for a given type are empty.
public class IgnoreEmptyEnumerablesResolver : DefaultContractResolver
{
public static readonly IgnoreEmptyEnumerablesResolver Instance = new IgnoreEmptyEnumerablesResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (property.PropertyType != typeof(string) &&
typeof(IEnumerable).IsAssignableFrom(property.PropertyType))
{
property.ShouldSerialize = instance =>
{
IEnumerable enumerable = null;
// this value could be in a public field or public property
switch (member.MemberType)
{
case MemberTypes.Property:
enumerable = instance
.GetType()
.GetProperty(member.Name)
.GetValue(instance, null) as IEnumerable;
break;
case MemberTypes.Field:
enumerable = instance
.GetType()
.GetField(member.Name)
.GetValue(instance) as IEnumerable;
break;
default:
break;
}
if (enumerable != null)
{
// check to see if there is at least one item in the Enumerable
return enumerable.GetEnumerator().MoveNext();
}
else
{
// if the list is null, we defer the decision to NullValueHandling
return true;
}
};
}
return property;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With