Take the 2-minute tour ×

and thanks for looking.

Background Info

I am constructing a dynamic ExpandoObject in C# which is ultimately serialized into JSON and returned to a view:

var allObjectData = db.ObjectAttributes.Where(o=>o.id.Equals(some_id));

dynamic objAtt = new ExpandoObject();
foreach (var oa in allObjectData)
            var item = objAtt as IDictionary<String, object>;
            item[oa.attributeName] = oa.AttributeValue;                   

return SomeSerializationMethod(objAtt);

This results in a nice JSON object that would look something like this:

{"Title":"Cars","Color":"Red","Model":{"Name":"Explorer","Engine":"v6"}}  etc. . .

But then any additional properties of the same name in subsequent iterations simply overwrite the first. So if, on the next loop, we get "Color":"Blue", it will overwrite "Color":"Red".

Of course, this example is simplified pseudocode and in actuality, I have recursive methods for drilling down deep into data and constructing complex objects.

The Problem

My problem is that I don't know how to merge identical properties into a list. For example the Object above should ideally look like this:


PLEASE NOTE: I can't simply make each iteration it's own list because if I did, it will break the client-side template engine I am using. For example, I couldn't do this:

<p>${Cars}</p><ul>{{each Colors}}<li>${Color}</li>{{/each}}</ul>

Having the object returned in the proper structure would allow me to iterate through the JSON object on the client side in a predictable manner.

Any advice is greatly appreciated!

share|improve this question
How does valid JSON have multiple Color, Model, etc? In fact, since you are using IDictionary, only the last is kept...? –  Marc Gravell Dec 2 '11 at 18:25
I would actually say: don't merge conflicts into a list - otherwise it will be different layout for single vs multiple values. I would say: create a DTO where it is always a list, even if it contains 0 or 1 items –  Marc Gravell Dec 2 '11 at 18:28
Marc, you are absolutely correct. In my haste to post this question I gave a bad example; only one "colors" would be kept. To your second point, if everything is a list, then it breaks the jQuery template engine I am using on the client side, so I cant set up a template that looks like this: <p>${Cars}</p><ul>{{each Colors}}<li>${Color}</li>{{/each}}</ul>. Hope that makes more sense. –  Matthew Patrick Cashatt Dec 2 '11 at 18:46
Since JSON can't have multiple properties with the same name in a single object, can you change how you expect your JSON to look? –  Gabe Dec 2 '11 at 18:55

Your Answer



Browse other questions tagged or ask your own question.