How to serialize GUID as native UUID in BSON using JSON.NET

JSON.NET does not seem to want to serialize the GUID as its own BSU UUID, but instead displays the GUID as strings.

I tested BSON generation both from JObject (checking before serialization that JValue.Type == JTokenType.Guid ) and an anonymous type ( new { myUuid = new Guid() } ), in any case, no luck.

How to make JSON.NET serialize GUIDs as its own BSU UUID (16-byte binary value, subtype = 0x04)?

Code example:

 var source = new { myInteger = 123L, myFloat = 10.0f, myString = "hello", myUuid = Guid.NewGuid(), myBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7 }, myDatetime = DateTime.UtcNow, }; MemoryStream buffer = new MemoryStream(); BsonWriter writer = new BsonWriter(buffer); JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(writer, source); byte[] myBson = buffer.ToArray(); 
+4
source share
1 answer

The problem arises from this WriteValue implementation in BsonWriter (in version 4.5.0.0):

 public override void WriteValue(Guid value) { base.WriteValue(value); this.AddToken((BsonToken) new BsonString((object) value.ToString(), true)); } 

Pay attention to the second line, it writes Guid as a string, so you see the results that you have.

Using the following example:

 [TestMethod] public void TestMethod1() { var source = new { myUuid = Guid.NewGuid(), }; using (var buffer = new MemoryStream()) using (var writer = new BsonWriter(buffer)) { var serializer = new JsonSerializer(); serializer.Serialize(writer, source); byte[] myBson = buffer.ToArray(); } } 

I expect bytes starting at index 12 to be (according to spec ):

  • \0x05 to indicate the type of binary
  • Four int bytes (with value 16, binary data length)
  • \0x04 to specify the subtype of UUID
  • 16 bytes to represent Guid / UUID content.

This is obviously an error, and I filed an error for this in the problem tracker for Json.NET .

+3
source

All Articles