Reputation: 1101
In ServiceStack 3.9, when deserializing a JSON array that contains some nulls, the null values are deserialized as nulls, as I expected. However, when I then serialize the same array back to JSON again, the nulls turn into empty objects.
public class MyClass
{
public string Foo { get; set; }
}
[Fact]
public void Test()
{
var originalJson = "[{\"Foo\":\"Bar\"},null]";
var arr = ServiceStack.Text.JsonSerializer.DeserializeFromString<MyClass[]>(originalJson);
var result = ServiceStack.Text.JsonSerializer.SerializeToString(arr);
// output is actually: [{"Foo":"Bar"},{}]
Assert.Equal(originalJson, result); // fails
}
Is this expected behavior? Or is there another way to serialize an array containing some nulls, and have the null items appear in JSON as nulls rather than as empty objects?
Note that when serializing an array of literals, like strings, null values are returned as null values, and not as objects.
Upvotes: 2
Views: 435
Reputation: 21521
I had this problem too. I found that if the array is cast to object[]
before calling SerializeToString()
then the null
values are output as expected.
var result = ServiceStack.Text.JsonSerializer.SerializeToString((object[])arr);
// result is correct [{"Foo":"Bar"}, null]
You can globally set the serialization of MyClass
using this JsConfig
:
JsConfig<MyClass[]>.RawSerializeFn = (obj) => ((object[])obj).ToJson();
Upvotes: 1