简体   繁体   中英

Mongo C# Driver and ObjectID JSON String Format

Is it possible to force the JsonWriterSettings to output the ObjectID as

{ "id" : "522100a417b86c8254fd4a06" }

instead of

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

I know I could write my own parser, but for the sake of code maintenance, I would like to find away to possibly override the Mongo JsonWriterSettings .

If this is possible, what classes/Interfaces should I override?

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

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

That way, you can refer to the type as a string normally (including serialization), but when MongoDB serializes it, etc., it's internally treated as an ObjectId. Here's using the class map technique:

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

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

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

I am using MongoDB.Driver with version 2.15.1 and for me is working this simple solution:

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

You do not have to specify attribute [BsonId] if the property name is "Id" The driver uses naming conventions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM