3

Suppose I have a class containing a member with bool? type.

public class Request
{
    public bool? IsOk {get; set;}
}

I expect ServiceStack's JSON deserializer that any values other than true or false in a JSON string result in null for this member. But sometimes it results in false, and sometimes it results in null!

There is a sample code in gistlyn that shows this issue.

Why does this happen? Is there any configuration to force strict parsing?

a3dho3yn
  • 33
  • 4

1 Answers1

2

By default ServiceStack's Text serializers tries to deserialize as much as possible without error. You can set JsConfig.ThrowOnError=true; (or Env.Strict=true in latest v5.1.1+ on MyGet) if you want the JSON Serializer to throw on deserialization error.

Or you can instead log any serialization errors to the console with:

Tracer.Instance = new ConsoleTracer();

The difference in behavior is that due to popular conventions values such as 1, "1" and "on" are also treated as true any other <2 characters are treated as false. Any other string value tries to deserialize into a boolean, e.g. "true" or "false", if it's none of these values it results in a deserialization error which by default is swallowed and the property is left unset (i.e. null).

But I've normalized behavior in this commit so only conventional values like true, 1, t, Y, on deserializes to true and their contra values false, 0, f, N, off deserializes to false and all other values tries to deserialize to a boolean (i.e. True/False) and will result in a deserialization error if fails.

This change is available from v5.1.1 that's now available on MyGet.

mythz
  • 141,670
  • 29
  • 246
  • 390
  • There was no deserialization error in my case. "fu" was neither <2 nor one of those values and was parsed to false (instead of null). Accordingly, setting `JsConfig.ThrowOnDeserializationError = true;` did not lead to an error. I've read the code, `length <= 2` is correct (not <2) – a3dho3yn Jul 18 '18 at 07:00
  • @a3dho3yn 2 chars and under it resolves to a bool value, false when it didn't match a true value. It now checks for specific true/false values. – mythz Jul 18 '18 at 07:02