Re: [mongodb-user] What is _t in a JSON de-serialised from a C# Object for?

3,328 views
Skip to first unread message

Robert Stam

unread,
Apr 22, 2013, 8:26:54 AM4/22/13
to mongod...@googlegroups.com
You are correct in assuming that the _t field holds the type of the object. The _t field is only added when the actual type of the object being serialized is different than the nominal type. For example:

var obj = "abc";
var json = obj.ToJson(); // nominal type is object, actual type is string

You can deserialize the resulting JSON as follows:

var rehydrated = BsonSerializer.Deserialize<object>(json); // nominal type is object, actual type will be determined from _t field


On Mon, Apr 22, 2013 at 8:15 AM, <richar...@gmail.com> wrote:
If I apply MongoDB.Bson.BsonExtensionMethods.ToJSON to a C# object:
i.e.

Object.ToJson()

I get a string with a _t element that records the type of the C# object.

I was assuming that this would then allow me to de-serialize the JSON string back into the Object using the _t type without having to specify the type in code.

This does not seem to be the case. Which is a shame as it would be very useful when dealing with serialising/de-serialising types that are only known at run time.

As _t is not for this, what is it for.

--
--
You received this message because you are subscribed to the Google
Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com
To unsubscribe from this group, send email to
mongodb-user...@googlegroups.com
See also the IRC channel -- freenode.net#mongodb
 
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

richar...@gmail.com

unread,
Apr 22, 2013, 10:33:09 AM4/22/13
to mongod...@googlegroups.com
Thanks for that; it was very useful.

I note that if the type being rehydrated is from a different assembly then the driver throws an error
"Unknown discriminator value..."

It's interesting that the driver can "find" the type for serializing but not for rehydrating.

It works fine if I assign the type using RegisterClassMap.

Robert Stam

unread,
May 9, 2013, 11:18:04 AM5/9/13
to mongod...@googlegroups.com
I don't think it matters whether the type is from a different assembly or not, the only thing that should matter is whether the discriminator value has been registered or not.

The reason it can automatically find the type when serializing is that it has a reference to the instance being serialized, and it can interrogate the type of the instance. When deserializing all it has is the _t value, so if that discriminator value has not been registered then it can't figure out what the actual type of the object should be.


--
Reply all
Reply to author
Forward
0 new messages