8

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.

Sally Richter
  • 271
  • 2
  • 9
  • If you're just looking for a way to convert the `JObject` to a nested structure of plain .NET objects (e.g. Dictionaries, Lists and primitives) you could try `ToObject()` helper method found in [this answer](https://stackoverflow.com/a/19140420/10263). – Brian Rogers Jul 22 '18 at 04:57

0 Answers0