Document that subclasses Dictionary<string,bool> no longer Load'able on 4.2

71 views
Skip to first unread message

Josh Buedel

unread,
May 23, 2019, 12:06:18 PM5/23/19
to RavenDB - 2nd generation document database
We have a document class named FeatureFlag that inherits from Dictionary<string,bool>. On 4.2, we get exceptions when loading it. It worked fine on 3.5.  The attached unit test demonstrates the problem. Use the #define at the top to switch between 3.5 and 4.2.

The exception is "Newtonsoft.Json.JsonReaderException : Error reading boolean. Unexpected token: StartObject. Path '@metadata'."
UnitTests1.cs

Egor Shamanaev

unread,
May 26, 2019, 5:45:37 AM5/26/19
to RavenDB - 2nd generation document database
Hello,
we are using the Json.Net library for serialization,
the library handles dictionaries without converting custom fields on class that inherits from dictionary. you can check that by var json = JsonConvert.SerializeObject(obj);
You can CustomizedJsonSerializer and register it in store conventions

For you example it should be something like this:
    public class FeatureFlagsConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            var val = (FeatureFlags)value;

            writer.WriteStartObject();
            writer.WritePropertyName(nameof(val.DocumentID));
            writer.WriteValue(val.DocumentID);

            foreach (var kvp in val)
            {
                writer.WritePropertyName(kvp.Key);
                writer.WriteValue(kvp.Value);
            }

            writer.WriteEndObject();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // TODO
            return null;
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(FeatureFlags);
        }
    }

Josh Buedel

unread,
May 31, 2019, 5:03:41 PM5/31/19
to RavenDB - 2nd generation document database
Thanks for the idea Egor. We ended up moving the dictionary to be a member variable, like below. Storing a dictionary directly isn't necessarily a use case we specifically need. It worked on 3.5 so this was more of a bug report than anything.

   public class FeatureFlags  
   {
      public Dictionary<string, bool> Flags = new Dictionary<string, bool>();
Reply all
Reply to author
Forward
0 new messages