[CSHARP-2599] Need to serialize a property that can come as a single object or an object array Created: 25/Apr/19  Updated: 25/Jun/20  Resolved: 25/Jun/20

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

Type: Bug Priority: Major - P3
Reporter: Rafael Gianine Assignee: Wan Bachtiar
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Hi there.

I faced and exception today and don't quite know how to work around it. Couldn't find anything similar online aswell.

So, I consume a webservice, and it returns me an xml that I convert to a json and later on save it to a Mongo database. I'm saving it as BsonDocument, once I don't know every property on the json to map a working C# model (I can't ensure that the property will always be the same).
Later on the code, I retrive that information to a previously maped model class and I add the "BsonIgnoreExtraElements" annotation to it. Inside that class, I've got a List<> property, but in my json the equivalent of that property, it's a single object, not an array.

Is there anyway that I force that value to always be serialized as an array? Even if on the mongo database it was saved as a single.

Thanks !



 Comments   
Comment by Wan Bachtiar [ 05/Jun/19 ]

Is there anyway that I force that value to always be serialized as an array? Even if on the mongo database it was saved as a single.

Hi Rafael,

You can register a custom serializer for a particular model to be treated with a special case. See also mongo-csharp-driver: Serialization.

Also I'd recommend to enforce the value consistency when, not after, writing to MongoDB.

Please note that the CSHARP project is for reporting bugs or feature suggestions for the MongoDB .NET/C# driver. If you have any follow-up questions on the use of the C# driver, please post a question on mongodb-user group with the relevant information. i.e. MongoDB .NET/C# driver version, example documents, example models, etc. 

Regards,
Wan.

Comment by Jeremy Mikola [ 25/Apr/19 ]

rafaelgianine: You originally opened this issue in the CDRIVER project, which tracks the C driver. I've moved this issue of to the CSHARP project, where it will hopefully get the attention of the C# driver developers.

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