Reputation: 5172
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?
Upvotes: 5
Views: 5867
Reputation: 5672
So I have this working with Dictionary<>
rather than IDictionary<>
without an custom converters, but I'm also using my own types rather than just object
. I'm not clear what you mean by "useful way", but you can annotate your members with BsonDictionaryOptionsAttribute
and pass in DictionaryRepresentation.Document
or DictionaryRepresentation.ArrayOfDocument
to change the shape persisted to MongoDB if that's what you mean?
Otherwise, what did you mean by "useful way" with regards to the way it's structured now? You'll alwways get the "_t"
discriminator as long as there's more than one type possible. I'm guessing that you're seeing that because you're using IDictionary<>
.
Upvotes: 3