3

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

laurencee
  • 818
  • 1
  • 7
  • 15
  • This is similar to http://stackoverflow.com/questions/14881270/is-there-a-way-to-ignore-default-values-during-serialization-with-servicestack-j but this question was not answered in that other stack overflow question. – laurencee May 22 '15 at 00:19

1 Answers1

1

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.

mythz
  • 141,670
  • 29
  • 246
  • 390