How to avoid sending null fields with JsonFX

540 Views Asked by At

In the codebase I am woking on, the most common object that is serialized in json has 3 fields. The value of one of these fields is often, but not always, null.

I was asked to avoid sending the field in the json build if its value is null. And I don't see how to do it. The JsonFX Annotations I know only allow to ignore a field whatever its value (JsonIgnore), or to transform the value of a field (using JsonName and properties )

1

There are 1 best solutions below

1
dbc On

If you want to skip nulls unconditionally for all properties and fields of all types, you can subclass your IResolverStrategy (which is likely JsonResolverStrategy or PocoResolverStrategy), override GetValueIgnoredCallback(MemberInfo member), and return a delegate that skips null values:

public class SkipNullJsonResolverStrategy : JsonResolverStrategy // Or PocoResolverStrategy
{
    public override ValueIgnoredDelegate GetValueIgnoredCallback(MemberInfo member)
    {
        Type type;
        if (member is PropertyInfo)
            type = ((PropertyInfo)member).PropertyType;
        else if (member is FieldInfo)
            type = ((FieldInfo)member).FieldType;
        else
            type = null;

        var baseValueIgnored = base.GetValueIgnoredCallback(member);
        if (type != null && (!type.IsValueType || Nullable.GetUnderlyingType(type) != null))
        {
            return (ValueIgnoredDelegate)((instance, memberValue) => (memberValue == null || (baseValueIgnored != null && baseValueIgnored(instance, memberValue))));
        }
        else
        {
            return baseValueIgnored;
        }
    }
}

Then use it like:

        var settings = new DataWriterSettings(new SkipNullJsonResolverStrategy());
        var writer = new JsonWriter(settings);

        var json = writer.Write(rootObject);

If you only want to skip nulls on selected properties, you need to use JsonResolverStrategy (or a subclass), and then either

For instance:

public class ExampleClass
{
    [JsonSpecifiedProperty("NameSpecified")]
    public string Name { get; set; }

    bool NameSpecified { get { return Name != null; } }

    [DefaultValue(null)]
    public int? NullInteger { get; set; }

    [DefaultValue(null)]
    public DateTime? NullableDateTime { get; set; }
}