Mongo C # Driver and ObjectID JSON String Format

Is it possible to get JsonWriterSettings to output ObjectID as

 { "id" : "522100a417b86c8254fd4a06" } 

instead

 { "_id" : { "$oid" : "522100a417b86c8254fd4a06" } 

I know that I can write my own parser, but for the sake of serving the code, I would like to find an opportunity to override Mongo JsonWriterSettings .

If possible, which classes / interfaces should I override?

+6
source share
2 answers

If you're fine using the MongoDB C # or Mapper attributes, you can do something like this:

 public class Order { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } } 

So you can usually refer to a type as a string (including serialization), but when MongoDB serializes it, etc., it is internally treated as an ObjectId. Here, using the class map method:

 BsonClassMap.RegisterClassMap<Order>(cm => { cm.AutoMap(); cm.SetIdMember(cm.GetMemberMap(c => c.Id); cm.GetMemberMap(c => c.Id) .SetRepresentation(BsonType.ObjectId); }); 
+6
source

If you use JSON.NET, then it's easy to add a JsonConverter that converts ObjectId values ​​to strings and vice versa.

In ASP.NET WebAPI, you can add this to the default set of converters in Formatters.JsonFormatter.SerializerSettings.Converters

0
source

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


All Articles