Reputation: 28530
I have a dynamic object being used as a parameter on a ApiController
. e.e:
public class Shape
{
public dynamic Coordinates { get; set; }
public string Id { get; set; }
public string Type { get; set; }
}
The coordinates for any shape are different, a circle will have a centre and radius, a line has an x1, y1, x2, y2 etc.
I am trying to store this object in Mongo.
What I am hoping for is:
{
"Shapes": [
{
"Coordinates": {
"x1": 1,
"y1": 2,
"x2": 3,
"y2": 4
}
},
"Type": "line"
},
{
"Coordinates": "{ "x" : 10, "y" : 20, "r" : 30,},
"Type": "circle"
}
],
}
When I use BsonExtensionMethods.ToJson(coordinates)
I get
{
"Shapes": [
{
"Coordinates": "{ \"x1\" : [], \"y1\" : [], \"x2\" : [], \"y2\" : [] }",
"Type": "line"
}
],
}
When I use (JObject) coordinates
I get:
{
"Shapes": [
{
"Coordinates": {
"_t": "Newtonsoft.Json.Linq.JObject, Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed",
"_v": {
"x1": [
],
"y1": [
],
"x2": [
],
"y2": [
]
}
},
"Type": "line"
}
],
}
I'd rather not haver to resort to storing it as a string. How do I convince .NET that I want to store the dynamic object's values?
Upvotes: 1
Views: 2540
Reputation: 503
Having done something similar in a different NoSQL database (FatDB) that has a similar issue, have you considered using JSON.NET to serialize it to a string and simply store the string in a class?
If you use an ExpandoObject (a type of dynamic object), you should be able to serialize it, toss the results into a string that goes into MongoDB and pull it out later on using a uniqueId. I have not tried that specifically with MongoDB, but at that point your dynamic object is nothing more than a string. When you pull it out, you de-serialize the JSON and you have your ExpandoObject back.
Upvotes: 0
Reputation: 381
Dynamic type is not support by MongoDB C# driver so far, sadly. But it is planned to be included in v2.0
.
Probably towards the end of year, likely in conjunction with server 2.6.
You could track this issue here and vote for this feature. https://jira.mongodb.org/browse/CSHARP-539
Upvotes: 1