Prevent serializing default values ​​with ServiceStack Json

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

I don't want to serialize these properties if they are the default, as it ends up taking up quite a bit of bandwidth and in my situation these extra bytes matter. It also makes reading the logs more effort as these defaults are serialized, creating a lot of unnecessary noise.

I know you can use JsConfig.SerializeFn and RawSerializeFn to return null in this situation, but that will also affect the list, which is not desired.

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

      

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

One alternative I can think of is to use nullable types (like int?) Instead and set them to null rather than 0 to prevent serialization, but that would involve changing a large number of contracts ...

Another option is to drop the 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

+3


source to share


1 answer


You can use values ​​with a null value, for example int?

, in which case the values null

will not be selected by default.

You can suppress the defaults by annotating individual properties with [DataMember(EmitDefaultValue = false)]

, for example:

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

      

Finally, I just added support for excluding default values ​​globally:



JsConfig.ExcludeDefaultValues = true;

      

Where suppresses serialization of default values.

This feature is available from v4.0.41 + , which is now available in MyGet .

+1


source







All Articles