[CSHARP-2398] BsonSerializer needs a PopulateObject method Created: 26/Sep/18  Updated: 27/Oct/23  Resolved: 26/Oct/18

Status: Closed
Project: C# Driver
Component/s: BSON
Affects Version/s: None
Fix Version/s: None

Type: New Feature Priority: Minor - P4
Reporter: PJ Legendre Assignee: Robert Stam
Resolution: Works as Designed Votes: 0
Labels: feature
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

MongoDB .NET Driver


Backwards Compatibility: Fully Compatible

 Description   

We want to deserialize a BsonDocument into an object and only overwrite the properties specified in the BsonDocument.

Json.NET has JsonConvert.PopulateObject(String, Object)

Unity has JsonUtility.FromJsonOverwrite(String, Object)

Having BsonSerializer.PopulateObject(String, Object) would be very helpful.



 Comments   
Comment by PJ Legendre [ 26/Oct/18 ]

Okay great solution thank you!

Comment by Robert Stam [ 26/Oct/18 ]

Our serializers are designed to return newly created objects, not to modify existing ones.

You can simulate what you want using an extension method:

public static class PopulateObjectExtension
{
    public static T PopulateObject<T>(this T value, BsonDocument changes)
    {
        var document = value.ToBsonDocument();
        document = document.Merge(changes, overwriteExistingElements: true);
        return BsonSerializer.Deserialize<T>(document);
    }
} 

This works by serializing the value to a BsonDocument and then altering that BsonDocument before deserializing it back.

If you don't want it to be an extension method you can package it as a regular static method instead.

Here's an example of the workaround in use:

public class C
{
    public int X { get; set; }
    public int Y { get; set; }
}
 
public static class Program
{
    public static void Main(string[] args)
    {
        var document = new C { X = 1, Y = 2 };
        var changes = BsonDocument.Parse("{ Y : 3 }");
        var changed = document.PopulateObject(changes);
    }
}

Generated at Wed Feb 07 21:42:26 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.