Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to flatten an ExpandoObject returned via JsonResult in asp.net mvc?
    primarykey
    data
    text
    <p>I really like the <code>ExpandoObject</code> while compiling a server-side dynamic object at runtime, but I am having trouble flattening this thing out during JSON serialization. First, I instantiate the object:</p> <pre><code>dynamic expando = new ExpandoObject(); var d = expando as IDictionary&lt;string, object&gt;; expando.Add("SomeProp", SomeValueOrClass); </code></pre> <p>So far so good. In my MVC controller, I want to then send this down as a JsonResult, so I do this:</p> <pre><code>return new JsonResult(expando); </code></pre> <p>This serializes the JSON into the below, to be consumed by the browser:</p> <pre><code>[{"Key":"SomeProp", "Value": SomeValueOrClass}] </code></pre> <p><b>BUT, what I'd really like is to see this:</b></p> <pre><code>{SomeProp: SomeValueOrClass} </code></pre> <p>I know I can achieve this if I use <code>dynamic</code> instead of <code>ExpandoObject</code> -- <code>JsonResult</code> is able to serialize the <code>dynamic</code> properties and values into a single object (with no Key or Value business), <i>but the reason I need to use <code>ExpandoObject</code> is because I don't know all of the properties I want on the object until runtime</i>, and as far as I know, I cannot dynamically add a property to a <code>dynamic</code> without using an <code>ExpandoObject</code>.</p> <p>I may have to sift through the "Key", "Value" business in my javascript, but I was hoping to figure this out prior to sending it to the client. Thanks for your help!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload