6

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?

1
  • I wouldn't recommend changing the way the deserialization is done. It's most likely written in a way that makes sense for the object structure. Instead I'd model my object I'm serializing to match the format. namespace object { class id { oid id; } class oid { String id } }. Something like that. Commented Sep 3, 2013 at 16:49

3 Answers 3

6

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);
});
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.