At the project I am working on, we started to use the Json.Net library.
However, I just found out that json.net is ‘loose’ on string type.
Here’s an example:
The DTO class
[JsonObject]
public class DTO
{
[JsonProperty]
public string type;
}
The deserialization
byte[] rawBody = GetBytes(@"{""type"":true}");
using (MemoryStream ms = new MemoryStream(rawBody))
{
using (StreamReader sr = new StreamReader(ms))
{
var serializer = new JsonSerializer();
return serializer.Deserialize(sr, typeof(DTO));
}
}
This will deserialize the ‘type’ attribute as “True”. However, I would expect it to fail and throw an exception as there’s a type mismatch.
It does the same if I replace true by 1 in the json. The property ‘type’ value will be “1”.
questions:
-
Is there a way to enforce strict serialization?
-
Is there other types than string that have implicit conversion like what we see here?
Thank you.
JF
I came up with a workaround.
Although it works, I don’t know if it is the good way to solve my ‘problem’.
I used converters to convert from
Here’s what I did:
The custom converter:
The deserialization:
Is there any type missing in this approach?
Does any one around have a better solution?
Thank you.