Is it best practice to deserialize and null reference - set to null or ignore?

This is a question about serialization in general, but in particular I use ServiceStack's excellent serializers in my .NET code.

Should deserializers set null property references? It looks like it is currently ignoring null references and just allowing you to set such fields according to the class defaults. For example, this test fails:

[TestMethod] public void Deserialize_WithNullCollection_CollectionIsNull() { var serializer = new ServiceStack.Text.TypeSerializer<Foo>(); Foo item = new Foo() { Strings = null }; Foo result = serializer.DeserializeFromString(serializer.SerializeToString(item)); Assert.IsNull(result.Strings); } public class Foo { public Foo() { Strings = new List<string>(); } public List<string> Strings { get; set; } } 

I believe that perhaps this test should succeed, but it is not ... - it is an empty list, not a null reference. It seems to me that null references are part of the state of the object, like any actual reference. Right or wrong?

+4
source share
1 answer

This is by design.

By default (to save bandwidth) ServiceStack text serializers do not allocate null to the wire. If the generated JSON is not null , then the property will not be set when it is deserialized, so it takes the default value specified in the constructor.

You can enable null values ​​with:

 JsConfig.IncludeNullValues = true; 

This is a static property (Shared), so setting it must be applied globally in the process.

This test passes when using JsonSerilaizer :

  [Test] public void Deserialize_WithNullCollection_CollectionIsNull() { JsConfig.IncludeNullValues = true; var item = new Foo { Strings = null }; var json = JsonSerializer.SerializeToString(item); var result = JsonSerializer.DeserializeFromString<Foo>(json); Assert.IsNull(result.Strings); } public class Foo { public Foo() { Strings = new List<string>(); } public List<string> Strings { get; set; } } 

It does not work in JSV format (ie TypeSerializer ), which does not support null values, since it cannot distinguish it from the string literal "null" . Therefore, if you want to use the JSV TypeSerializer, you must assume that null means the default property values ​​for the type (i.e. as specified in the default constructor).

+4
source

All Articles