Search code examples
c#servicestack-text

Prevent serializing default value types with ServiceStack Json


Some of my contracts have quite a few int/decimal/short/byte etc. properties which often have default values.

I don't want to serialize these properties if they are default values as that ends up taking quite a bit of bandwidth and in my situation those extra bytes do make a difference. It also makes reading logs take more effort since having those default values serialized creates a lot of unnecessary noise.

I am aware that you can use the JsConfig.SerializeFn and RawSerializeFn to return null in this situation but that will also affect List which is not desirable.

JsConfig<int>.SerializeFn = value => value == 0 ? null : value.ToString();

Is there some other way to prevent these values from being serialized?

One alternative I can think of is to make them nullable types instead (e.g. int?) and set their value to null rather than 0 to prevent the serialization but that will involve changing a large number of contracts...

Another alternative is to give up on ServiceStack for json serialization and use Json.NET which supports this out of the box: http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DefaultValueHandling.htm


Solution

  • You could use nullable values e.g int? in which case null values are not emitted by default.

    You could suppress default values by annotating individual properties with [DataMember(EmitDefaultValue = false)], e.g:

    [DataContract]
    public class Poco
    {
        [DataMember(EmitDefaultValue = false)]
        public int DontEmitDefaultValue { get; set; }
    }
    

    Finally I've just added support for excluding default values globally with:

    JsConfig.ExcludeDefaultValues = true;
    

    Where suppresses serializing default values of value types.

    This feature is available from v4.0.41+ that's now available on MyGet.