コード例 #1
0
 private void WriteNested(BsonWriterAdapter adapter, Action writer)
 {
     adapter.WriteStartObject();
     adapter.WritePropertyName("x");
     writer();
     adapter.WriteEndObject();
 }
コード例 #2
0
        protected byte[] SerializeUsingNewtonsoftWriter <T>(T value, bool mustBeNested = false, GuidRepresentation guidRepresentation = GuidRepresentation.Unspecified)
        {
            using (var memoryStream = new MemoryStream())
                /*
                 *
                 * The Newtonsoft.Json.Bson.BsonDataWriter cannot be used for Guids with `GuidRepresentation.CSharpLegacy`
                 * because it will always write Guids with with BinaryData subtype `0x04` that map to `BsonBinaryType.Uuid`.
                 * `BsonBinaryType.OldUuid` would write the required BinaryData subtype (`0x03`), but there is no way to
                 * force its use through the public API surface (the subtype it is actually hardcoded to `BsonBinaryType.Uuid`
                 * in the JsonNet codebase).
                 *
                 * The MongoDb BSON writer instead use BsonBinarySubType.UuidLegacy (`0x03`) when the type
                 * is `GuidRepresentation.CSharpLegacy`.
                 * The BinaryData subtype `0x04` map to `BsonBinarySubType.UuidStandard`, but it cannot be used
                 * because then the `Guid` bytes are written in network order (BigEndian) introducting more differences.
                 *
                 * This code has been modified to use the `BsonWriterAdapter` and to verify that Guids roundtrip
                 * correctly when using the adapter.
                 *
                 */

                //using (var newtonsoftWriter = new Newtonsoft.Json.Bson.BsonDataWriter(memoryStream))

                using (var writer = new BsonBinaryWriter(memoryStream, new BsonBinaryWriterSettings {
                    GuidRepresentation = GuidRepresentation.CSharpLegacy
                }))
                    using (var newtonsoftWriter = new BsonWriterAdapter(writer))
                    //
                    {
                        if (mustBeNested)
                        {
                            newtonsoftWriter.WriteStartObject();
                            newtonsoftWriter.WritePropertyName("x");
                        }

                        var newtonsoftSerializer = new Newtonsoft.Json.JsonSerializer();
                        newtonsoftSerializer.Serialize(newtonsoftWriter, value);

                        if (mustBeNested)
                        {
                            newtonsoftWriter.WriteEndObject();
                        }

                        return(memoryStream.ToArray());
                    }
        }