将属性附加到匿名类型以与JavaScriptSerializer一起使用

时间:2014-10-30 12:31:31

标签: c# asp.net-mvc

我正在扩展JsonResult并需要向其中的Data属性添加属性。

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)
}

一种选择是将其转换为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;
}

但是当通过JavaScriptSerializer时,这将显示为:

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

当所需结果为:

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

我可以复制粘贴base.ExecuteResult(ControllerContext)实现并修改它以使用How to flatten an ExpandoObject returned via JsonResult in asp.net mvc?中发布的解决方案,但是当实现已经存在时,这似乎有点脏。

1 个答案:

答案 0 :(得分:0)

IDictionary<string, object>路线实际上是一种很好的方式,因为JavaScriptSerializer实际上正确地序列化了Dictionary<string, object>。因此,您需要做的就是使用IDictionary<string, object>并使用它实例化一个新的具体Dictionary<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 new Dictionary<string, object>(originalDictionary);
}