0

my C# class

public class User
{
    [BsonRepresentation(BsonType.ObjectId)]
    [Newtonsoft.Json.JsonProperty(PropertyName = "_id")]
    public string? Id { get; set; }

    [Newtonsoft.Json.JsonProperty(PropertyName = "name")]
    public string Name { get; set; }

    [Newtonsoft.Json.JsonProperty(PropertyName = "email")]
    public string Email { get; set; }
}

my mongodb json document

{ "_id": { "$oid": "63353few87yr8748wd8" }, "Name": "Rishabh", "Email": "Rishabh@gmail.com" }

expected json

*****{ "_id": { "$oid": "634376t7tegr78145d8" }, "name": "Rishabh", "email": "Rishabh.soni2@honeywell.com"

}*****

I want the property in small case is there any solution for it I have already tried with changing the class property by Name to name it worked but I don't want that way I just need to save the key name in small letter not the class property name. Please suggest any solution for it.

  • Do you mean you want to lowercase them, or that you want to camelCase them? Would ThisPropertyName become thispropertyname or thisPropertyName? – ProgrammingLlama Sep 29 '22 at 07:28
  • Depending on what you want, you'll either need to register `CamelCaseElementNameConvention`, or make your own name convention (for all lowercase). – ProgrammingLlama Sep 29 '22 at 07:30
  • The answer here may have what you are looking for https://stackoverflow.com/questions/6288660/ensuring-json-keys-are-lowercase-in-net – Coop Sep 29 '22 at 07:52

1 Answers1

0

By default, MongoDB maps the property names as they are to the BSON property names. If it is only about some properties that you want to change, you can mark them with BsonElement attributes and specify the name, e.g.

public class User
{
    [BsonRepresentation(BsonType.ObjectId)]
    [Newtonsoft.Json.JsonProperty(PropertyName = "_id")]
    public string? Id { get; set; }

    [Newtonsoft.Json.JsonProperty(PropertyName = "name")]
    [BsonElement("name")]
    public string Name { get; set; }

    [Newtonsoft.Json.JsonProperty(PropertyName = "email")]
    [BsonElement("email")]
    public string Email { get; set; }
}

However, if you want to change the naming convention in one place, you can use the CamelCaseElementNameConvention like this at the beginning of your application:

var pack = new ConventionPack();
pack.Add(new CamelCaseElementNameConvention());
ConventionRegistry.Register(
 "CamelCaseElementNameConvention",
 pack,
 t => t.FullName.StartsWith("MyNamespace."));

See this link for details.

Markus
  • 20,838
  • 4
  • 31
  • 55