user3791372
user3791372

Reputation: 4665

Serializing ExpandoObject with json.Net

I have the following code, where page.Fields is an ExpandoObject. I'm iterating through some user-defined properties and adding them to an Expando, cast to an IDictionary<string,string> to allow me to add new field name / values dynamically, but when I set the Fields property to the value of props, serializing afterwards only gives names with blank values of {}. Why?

page.Fields.Foo = "asdf";
var test = JsonConvert.SerializeObject(page); // shows Foo=asdf in the json

// attach all fields to the page object, casting to an IDictionary to be able to add var names
var props = new ExpandoObject() as IDictionary<string, Object>;
foreach (string key in Request.Form.Keys)
{
    if (key.StartsWith("Fields."))
    {
        var fieldName = key.Substring(key.IndexOf(".") + 1);
        props.Add(fieldName, Request.Form[key]);
    }
}

var test2 = JsonConvert.SerializeObject(props); // blank values of {}
page.Fields = props as ExpandoObject;

// loses the values for the Fields property
test = JsonConvert.SerializeObject(page);

UPDATE the curse of Nancy strikes, the Request.Form values turned out to be dynamic, so I had to .ToString() it to make it fit into the expected IDictionary<string,string>

Upvotes: 2

Views: 5819

Answers (2)

Hemant Sharma
Hemant Sharma

Reputation: 40

I'm suspect it's a defect and you are not getting anything for Request.Form.Keys that's matches Field. criteria.

your code works fine for me if I've a page class with dynamic Fields property

Upvotes: 0

Gusman
Gusman

Reputation: 15151

To correctly serialize the data you must declare the variable as dynamic, not as an ExpandoObject, JSON .net uses reflection to retrieve properties, if it's a dynamic it casts it as an ExpandoObject and uses the keys as property names, but if you pass the ExpandoObject directly it tries to retrieve the properties from the ExpandoObject type.

Just change

var props = new ExpandoObject() as IDictionary<string, Object>;

to

var props = new ExpandoObject();
var iProps = props as IDictionary<string, Object>;

Use iProps to add the data and pass props to the serialization.

EDIT:

You're storing the value in "Page.Fields", this must be dynamic also.

Upvotes: 4

Related Questions