简体   繁体   中英

Deserialize flat MongoDB document to a nested C# class

I am adding an API to an existing database so I am stuck with the current MongoDB document schema. The document is flat with no nested objects. I want to deserialize a group of the fields into a child object. I was wondering if there was a way of doing that with the BsonElement attribute? Another approach I came across was using a custom serializer. Would it be possible to write a custom serializer for the child object even though there is no field matching the child object's name? Or would I need to write the custom serializer at using the parent object?

Here is an example of a document:

{
  "Name": "Name",
  "AddressLine1": "321 street",
  "AddressLine2": "apt 1",
}

Here is an example of the C# classes and what I was trying to do:

public class Customer 
{
    [BsonElement("Name")]
    public string CustomerName {get; set;}

    public Address Address {get; set;}   
}

public class Address 
{
   [BsonElement("AddressLine1")]
   public string AddressLine1 {get; set;}

   [BsonElement("AddressLine2")]
   public string AddressLine2 {get; set;}
}

There's no way to use attributes to achieve what you are wanting, this because the attributes apply given conditions to a BsonMemberMap which resides in the BsonClassMap.

As you said this however can be achieved by creating a custom serializer.

public class CustomBsonSerializer : IBsonSerializer<MyType>
{
   
}

BsonSerializer.RegisterSerializer(new CustomBsonSerializer())

However, if you want to write a bespoke serializer it can become a bit brittle.

I'd personally opt for creating 2 sets of models, one to model the current state of your documents in MongoDB and then another model to create the structure that you want to use.

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