Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.net loose vs strict type deserialization

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:

  1. Is there a way to enforce strict serialization?

  2. Is there other types than string that have implicit conversion like what we see here?

Thank you.

JF

like image 367
Jean-Francois Avatar asked Nov 07 '12 15:11

Jean-Francois


1 Answers

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:

[JsonObject]
public class DTO
{
    [JsonProperty]
    public string type;
}

The custom converter:

class JsonStrictConverter<T> : JsonConverter
    {
        public JsonToken[] TokenTypes { get; set; }

        public JsonStrictConverter(params JsonToken[] tokenTypes)
        {
            TokenTypes = tokenTypes;
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(T);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                if (objectType.IsValueType)
                {
                    return Activator.CreateInstance(objectType);
                }
                return null;
            }

            var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
            return (T)converter.ConvertFromString(reader.Value.ToString());
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException("The converter '" + this.GetType().Name + "' is not intended to be used when serializing.");
        }
        public override bool CanWrite { get { return false; } }
    }

The deserialization:

XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();
bodyReader.ReadStartElement("Binary");
byte[] rawBody = bodyReader.ReadContentAsBase64();
using (MemoryStream ms = new MemoryStream(rawBody))
{
    using (StreamReader sr = new StreamReader(ms))
    {
        var serializer = new JsonSerializer();
        /* These converter are present to enforce strict data type in the json. */ 
        /* by default, newtonsoft can serialize Numbers as strings, strings as boolean, etc.... */
        serializer.Converters.Add(new JsonStrictConverter<string>(JsonToken.String));
        serializer.Converters.Add(new JsonStrictConverter<bool>(JsonToken.Boolean));
        serializer.Converters.Add(new JsonStrictConverter<short>(JsonToken.Integer));
        serializer.Converters.Add(new JsonStrictConverter<ushort>(JsonToken.Integer));
        serializer.Converters.Add(new JsonStrictConverter<int>(JsonToken.Integer));
        serializer.Converters.Add(new JsonStrictConverter<uint>(JsonToken.Integer));
        serializer.Converters.Add(new JsonStrictConverter<long>(JsonToken.Integer));
        serializer.Converters.Add(new JsonStrictConverter<ulong>(JsonToken.Integer));
        serializer.Converters.Add(new JsonStrictConverter<float>(JsonToken.Float, JsonToken.Integer));
        serializer.Converters.Add(new JsonStrictConverter<double>(JsonToken.Float, JsonToken.Integer));
        serializer.Converters.Add(new JsonStrictConverter<decimal>(JsonToken.Float, JsonToken.Integer));

        return serializer.Deserialize(sr, typeof(DTO));                    
    }
}

Is there any type missing in this approach?

Does any one around have a better solution?

Thank you.

like image 88
Jean-Francois Avatar answered Sep 26 '22 01:09

Jean-Francois