The following class should be obtained by the API as Json and stored in MongoDB using the C # Driver and Web API. The data property is unstructured, but I can limit it to value keys with possible nested arrays in these values.
public class Something { [BsonId, JsonIgnore] public ObjectId _id { get; set; } public IDictionary<string, object> data { get; set; } }
When json is sent from the client, Json.NET is deserialized correctly.
Saving a class in MongoDB, I get something like this in a database with a specific C # type:
{ property1: 'one', property2: { _t: 'System.Collections.Generic.List`1[System.Object]' _v: [ {}, {}, {}, ... ] } }
Based on these sources, I compiled a CustomCreationConverter for Json.NET that inserts a list into the dictionary value:
Apply JsonDictionaryAttributes properties to properties
Json.NET: deserializing nested dictionaries
Source Code CustomCreationConverter
public class Something { ... [JsonProperty(ItemConverterType = typeof(CustomConverter))] public IDictionary<string, object> data { get; set; } }
with this override:
public class CustomConverter : CustomCreationConverter<IList<object>> { public override IList<object> Create(Type objectType) { return new List<object>(); } public override bool CanConvert(Type objectType) { return true; // Just to keep it simple } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.StartArray) return base.ReadJson(reader, objectType, existingValue, serializer); return serializer.Deserialize(reader); } }
This works fine, but I'm still getting a construct with specific C # types in MongoDB. How can I get this data in MongoDB without type properties when nested?