JamesNK / Newtonsoft.Json.Bson

Json.NET BSON adds support for reading and writing BSON to Json.NET
MIT License
55 stars 23 forks source link

Option to deserialize ObjectId into strict format #8

Open HappyNomad opened 6 years ago

HappyNomad commented 6 years ago

Mongo's BsonBinaryWriter serializes my complex document on the server, and Json.NET's BsonDataReader deserializes it to a JObject on the client. After deserialization, I replace _id ObjectIds with their string representations and then do the following for references:

foreach ( var reference in rootJObject.Descendants().OfType<JValue>().Where( v => v.Type == JTokenType.Bytes ).ToList() )
    reference.Replace( new JObject( new JProperty( "$ref", (string)reference ) ) );

This seems to work but relying on v.Type == JTokenType.Bytes to recognize the ObjectIds concerns me. Bytes is too general and could lead to false positives. I propose to improve the deserialization of BSON to provide a more sure way to recognize the ObjectIds.

In the original JSON with which I seeded the Mongo database, I represented ObjectIds in Mongo's strict JSON format of {$oid: "someObjectId"}. Upon deserializing to JObject, I propose an option that the ObjectIds is represented as such instead of the byte representation.