Save dictionary with nested array in MongoDB

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?

+4
source share
1 answer

So, this works for me with Dictionary<> , not IDictionary<> without custom translators, but I also use my own types, not just object . I don’t understand what you mean by the “useful way”, but you can annotate your members with a BsonDictionaryOptionsAttribute and pass to DictionaryRepresentation.Document or DictionaryRepresentation.ArrayOfDocument to change the form stored in MongoDB if that is what you mean ?

Otherwise, what did you mean by the “useful way” in relation to the way it is structured? You will receive the discriminator "_t" if more than one type is possible. I assume you see this because you are using IDictionary<> .

+2
source

Source: https://habr.com/ru/post/1446194/


All Articles