I have a WEB API web service that accepts an arbitrary Object that I would like to store as a property in a MongoDB document. By the time my class library gets it, it is a JObject, so simply storing it as is includes all sorts of extra cruft. I am brand new to mongo, and the only workaround I could figure out is to make the property of type BsonValue, and writing the following bit of hackery to create it:
private static BsonValue ToBsonValue(object value)
{
var jobject = value as Newtonsoft.Json.Linq.JContainer;
if (jobject != null)
{
return BsonDocument.Parse("{crazyHack: " + jobject.ToString() + "}")[0];
}
else
{
return BsonValue.Create(value);
}
}
When retrieving the value,I convert it back to an Object with BsonTypeMapper.MapToDotNetValue.
I can't imagine there isn't a more straightforward way to do this, but JContainer doesn't seem to have any methods that will generate a plain object that is not itself a JContainer. Any tips would be appreciated.