0

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 )

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
LBarret
  • 1,113
  • 10
  • 23

1 Answers1

1

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; }
}
dbc
  • 104,963
  • 20
  • 228
  • 340
  • 1
    Are you using JsonFx v1 or v2? If v2, then @dbc gave multiple good ways. If using v1, then use `[DefaultValueAttribute(null)]`. – mckamey Oct 27 '15 at 05:52