0

I am extending JsonResult and need to add properties to the Data property within it.

public override void ExecuteResult(ControllerContext context)
{
    // error checking removed for brevity

    this.Data = AppendSomehow(
                    this.Data, // = new { hello = "hi" }
                    new { goodbye = "bye" });

    base.ExecuteResult(context); // calls javaScriptSerializer.Serialize(this.Data)
}

One option is to convert it into an IDictionary<string, object>:

private static object AppendSomehow(object data, object additional)
{
    var originalDictionary = new RouteValueDictionary(original);
    var additionalDictionary = new RouteValueDictionary(additional);

    foreach (var kv in additionalDictionary)
        originalDictionary.Add(kv.Key, kv.Value);

    return originalDictionary;
}

but when passed through a JavaScriptSerializer this will come out as:

[{"Key":"hello","Value":"hi"},{"Key":"goodbye","Value":"bye"}]

when the desired result is:

{"hello":"hi","goodbye":"bye"}

I could just copy-paste the base.ExecuteResult(ControllerContext) implementation and modify it to use the solution posted in How to flatten an ExpandoObject returned via JsonResult in asp.net mvc? but that seems a bit dirty when the implemenation already exists.

Community
  • 1
  • 1
dav_i
  • 27,509
  • 17
  • 104
  • 136

1 Answers1

0

Going down the IDictionary<string, object> route is actually a good way to go as JavaScriptSerializer actually serializes Dictionary<string, object> correctly. As such all you need to do is take the IDictionary<string, object> and instantiate a new concrete Dictionary<string, object> with it.

private static object AppendSomehow(object data, object additional)
{
    var originalDictionary = new RouteValueDictionary(original);
    var additionalDictionary = new RouteValueDictionary(additional);

    foreach (var kv in additionalDictionary)
        originalDictionary.Add(kv.Key, kv.Value);

    return new Dictionary<string, object>(originalDictionary);
}
dav_i
  • 27,509
  • 17
  • 104
  • 136