Edit: I add array to the Json objects since the real case includes arrays.
I have a class element
that contains a property options
, the options class can in turn change its properties for example it could have these 2
element1 = {
"id":"1",
"options":{
"margenes":["24px","25px","0px","32px"],
"printable":"true",
"stackOverflow":"great"
}
}
element2 = {
"id":"2",
"options":{
"question":"awsome",
"propertyDiferent":"empty"
}
}
In the web api I have a method like this:
public object Post([FromBody] Element element)
{
SaveToMongo(element);
}
the element class:
public class Element
{
public dynamic options { get; set; }
public string id { get; set; }
}
When I fetch the Element from mongo I have no problems. But when I have to send it through the web api's post method it doesn't deserialize into an expando object like it does from mongo. How could I achieve similar behavior on both ends?
Basically I want that the passage of the object through the web api does not involve an effort. I have created the web-api simply because I was not able to attack mongo from javascript.
EDIT:
If what you need is a
ExpandoObject
you simply need to declare the main object asdynamic
so you can treat it as an Expando, otherwise I think you can't mix direct serialization to a class with an ExpandoObject in between. So the solution would be to declare the signature of the WebApi controller like so:ANCIENT:
If you want to serialize it, you should know the options that you can receive, even if you don't always receive them.
For this reason, you must create a new class
Options
that collects the properties that can arrive and also modify your classElement
so that the options property is of the new type created.Your class would look like this:
dynamic
it does not have a specific data type and therefore the deserializer cannot know what it is going to convert it to (for a reason the namedynamic
, right?). You have to use a concrete, defined data type that is possible to get all the metadata for the deserializer to work.Dictionary<string,string>
It is your best option since it is the representation of an object in the json notation.You can use Newtonsoft to deserialize the object and cast it to the class
Element
.For example:
Use:
I am not saying that this code will work for you. But now you have an alternative.
First step, make the call
ajax
from javascript pass the JSON in the form of a string, otherwise the options dynamic property is not filled.So I have a JSON string that, although it is saved in the mongo, I can retrieve it without being modified. But to be able to return it in the API I have to deserialize it before the deserialization that the controller itself does.
It's an inelegant system, with a few drawbacks, such as not allowing options to be handled in mongo. But it has been the only way in which I have achieved that the passage through the mongo did not modify the object.