I was suprised, that any valid json, even empty "{ }"
can be deserialized by JsonConvert.DeserializeObject as any T
class. The missing values will simply be default
.
To example, I can't do following
record Test(string must, string? optional); // "must" must be present in json
var input = "{ }";
if (JsonConvert.DeserializeObject<Test>(input) is Test test) { ... } // must = null, great, thanks
because deserialization is always successful and worse - must = null
(nullable context is completely ignored). Here is a fiddle.
I was expecting to receive null
instead of T
, despite there is nothing written in docs. My bad, I got it.
How should I deserialize json as T
only when it is T
? I can't change json to e.g. contain type info.
I was suprised, that any valid json, even empty "{ }"
can be deserialized by JsonConvert.DeserializeObject as any T
class. The missing values will simply be default
.
To example, I can't do following
record Test(string must, string? optional); // "must" must be present in json
var input = "{ }";
if (JsonConvert.DeserializeObject<Test>(input) is Test test) { ... } // must = null, great, thanks
because deserialization is always successful and worse - must = null
(nullable context is completely ignored). Here is a fiddle.
I was expecting to receive null
instead of T
, despite there is nothing written in docs. My bad, I got it.
How should I deserialize json as T
only when it is T
? I can't change json to e.g. contain type info.
1 Answer
Reset to default 1deserialize json as
T
only when it isT
Disclaimer: for me json is T
when all required by T
properties are present in json.
Use Required property to mark required properties:
record Test([property: JsonProperty(Required = Required.Always)]string must, string? optional);
JsonSerializationException is thrown if such property is missing, which can be handled with try/catch
.
Here is a fiddle with the fix.
input
were the stringnull
. A reference to an "empty" object (nothing set to a non-default value) is very, very different to a null reference. (Throwing an exception might be reasonable, but returning a null reference definitely wouldn't be IMO.) – Jon Skeet Commented Feb 3 at 11:52