'How to use camel case property names for a part of the object hierarchy for MongoDB

So far we have used JSON.NET in the project and we have around 10 to 15 custom converters. We have used MongoDB just as a key value store for many parts and therefore we have decided that we do not want to write the converters twice.

Therefore we have written a custom BsonConverter that acts as a bridge between Mongo and JSON.NET.

For example this is how our Mongo Entity class looks like:

class KeyValueEntity<T> {
   [BsonId]
   public string Key { get; set; }

   [BsonJson]
   public T Value { get; set; }
}

[BsonJson] is a custom attribute to use a custom serializer. This serializers works with JSON.NET and writes objects with a custom JsonWriter, which basically redirects everything to a BsonWriter. It is very efficient and also faster in many parts because the serialization part of JSON.NET seems to be faster. We have also used this [BsonJson] approach in a few other classes.

The problem is that we have now a mix of camelCase and PascalCase in the MongoDB documents.

We would like to migrate to System.Text.Json but the solution with the custom JsonWriter does not work anymore. We could implement something similar but this would only work, if we write the JSON to a buffer, then deserialize it again to write it to BSON afterwards. Not ideal.

So the "perfect" solution would be to have a way to tell MongoDB to use a camelCase from here on, but everything seems to be a global setting in MongoDB C# driver. For example custom serializers and conventions cannot be applied for a subset of the serialization logic.

Is there a solution for this problem?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source