The following class shall be received by an API as Json and stored in MongoDB, using the C# Driver and Web API. The data property is unstructured, but I can restrict it to key-value pairs with possibly nested arrays in these values.
public class Something
{
[BsonId, JsonIgnore]
public ObjectId _id { get; set; }
public IDictionary<string, object> data { get; set; }
}
When the json is posted from the client, Json.NET deserializes properly.
Saving the class to MongoDB, I get something like this in the database with the c# specific type:
{
property1: 'one',
property2: {
_t: 'System.Collections.Generic.List`1[System.Object]'
_v:
[
{}, {}, {}, ...
]
}
}
Based on these sources, I have pulled together a CustomCreationConverter for Json.NET that nests a List into the value of the Dictionary:
Apply JsonDictionaryAttributes to properties
Json.NET: Deserializing nested dictionaries
CustomCreationConverter Source Code
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 actually fine, but I still get the construction with the c# specific types in MongoDB. How can I get this data into MongoDB without the type-value properties when nested?