using System; using System.Collections.Generic; using System.Text.Json; namespace ln.bson.mapper.mappings { public class DictionaryMapping : BsonMapping { public DictionaryMapping() : base(typeof(Dictionary)) { } public override bool TryMapValue(BsonMapper mapper, object o, out BsonValue bsonValue) { if (mapper.TryGetMapping(typeof(T), out BsonMapping elementMapping)) { Dictionary d = (Dictionary)o; BsonDocument bsonDocument = new BsonDocument(); foreach (KeyValuePair keyValuePair in d) { if (!elementMapping.TryMapValue(mapper, keyValuePair.Value, out BsonValue elementValue)) { bsonValue = null; return false; } bsonDocument.Add(keyValuePair.Key, elementValue); } bsonValue = bsonDocument; return true; } bsonValue = null; return false; } public override bool TryMapValue(BsonMapper mapper, BsonValue bsonValue, out object o) { if (bsonValue is BsonDocument bsonDocument && mapper.TryGetMapping(typeof(T), out BsonMapping elementMapping)) { Dictionary d = new Dictionary(); foreach (KeyValuePair keyValuePair in bsonDocument) { if (!elementMapping.TryMapValue(mapper, keyValuePair.Value, out object element)) { o = null; return false; } d.Add(keyValuePair.Key, (T)element); } o = d; return true; } o = null; return false; } } }