This project has moved and is read-only. For the latest updates, please go here.

Bson Serialization / Deserialization of generic object

Aug 12, 2011 at 5:27 AM
Edited Aug 12, 2011 at 2:11 PM


I have been recently testing the Bson Serialization / Deserialization side of your library and have hit something that is causing me a bit of grief.  I am sure I have overlooked something, but I am at an impasse and thought I would reach out to you.  I have included a small amount test code below.  The primary problem is that when I set the object in the class to an Int32, serialize to a memorystream, then deserialize from the memorystream I end up with the object set to a long, but with the correct value.  I have verified that the value is being read from the stream correctly in the BsonReader.ReadType method as an Integer, yet the object in the deserialized class ends up being a long.  Another place you can see something odd happening is if you set the object to a class object.  The object serializes out of the byte array as a Newtonsoft.Json.Linq.JObject instead of the actual class.  Do you have any suggestions?

Thank you

simple class:
    public class Test1
        public int TestVal1 { get; set; }
        public object TestVal2 { get; set; }

simple console app:
    class Program
        static void Main(string[] args)
            Test1 t1 = new Test1();
            t1.TestVal1 = 12;
            t1.TestVal2 = (int)13;

            JsonSerializer Js = new JsonSerializer();
            MemoryStream Ms = new MemoryStream();
            BsonWriter Bw = new BsonWriter(Ms);

            Js = new JsonSerializer();
            Js.Serialize(Bw, t1);
            Ms.Position = 0;
            BsonReader Br = new BsonReader(Ms);

            Test1 xx = Js.Deserialize<Test1>(Br);


Watch window from debug:
-  t1 {BsonTest3.Test1} BsonTest3.Test1
  TestVal1 12 int
  TestVal2 13 object {int}
-  xx {BsonTest3.Test1} BsonTest3.Test1
  TestVal1 12 int
  TestVal2 13 object {long}


Apr 7, 2014 at 3:22 PM
Hi exeter

See this conversation (

Looks like it's a known problem with

Easiest solution is try and use a long. Maybe implement an intermediary class?

Or follow mruston's idea of customising the NewtonSoft source code to fix it.

Perhaps they'll fix it one day - who knows?