2

我正在构建一个使用 Open Flash Chart 2 的应用程序。此图表是一个 Flash 对象,它接受具有特定结构的 JSON。

"elements": [
{
    "type": "bar_stack",
    "colours": [
        "#F19899",
        "#A6CEE3"
    ],
    "alpha": 1,
    "on-show": {
        "type": "grow-up",
        "cascade": 1,
        "delay": 0
    },
    ...

我正在使用一个简单的匿名类型来返回 JSON,如下所示:

return Json(new
{
    elements = new [] {
        new
        {
            type = "bar_stack",
            colours = colours.Take(variables.Count()),
            alpha = 1,
            on_show = new
            {
                type = "grow-up",
                cascade = 1,
                delay = 0
            },
            ...
        }
}

问题是几个属性(如“on-show”)使用破折号,显然在 C# 代码中命名属性时我不能使用破折号。

有没有办法克服这个问题?最好不需要声明一大堆类。

4

2 回答 2

1

您可以使用字典:

return Json(new {
    elements = new [] {
        new Dictionary<string, object> 
        { 
            { "type", "bar_stack" },
            { "colours", new [] { "#F19899", "#A6CEE3" } },
            { "alpha", 1 },
            { "on-show", new 
                         {
                             type = "grow-up",
                             cascade = 1,
                             delay = 0
                         } },
        } 
    }
});

(写在 SO 编辑器中;我可能犯了一些语法错误,但你明白了......)

于 2012-08-24T14:54:13.050 回答
0

克雷格的解决方案可能更好,但同时我实现了这个:

public class UnderscoreToDashAttribute : ActionFilterAttribute
{
    private readonly string[] _fixes;

    public UnderscoreToDashAttribute(params string[] fixes)
    {
        _fixes = fixes;
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Filter = new ReplaceFilter(filterContext, s => _fixes.Aggregate(s, (current, fix) => current.Replace(fix, fix.Replace('_', '-'))));
    }

    public class ReplaceFilter : MemoryStream
    {
        private readonly Stream _stream;
        private readonly Func<string, string> _filter;

        public ReplaceFilter(ControllerContext filterContext, Func<string, string> filter)
        {
            _stream = filterContext.HttpContext.Response.Filter;
            _filter = filter;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
             // capture the data and convert to string 
            var data = new byte[count];
            Buffer.BlockCopy(buffer, offset, data, 0, count);

            var s = _filter(Encoding.Default.GetString(buffer));

            // write the data to stream 
            var outdata = Encoding.Default.GetBytes(s);
            _stream.Write(outdata, 0, outdata.GetLength(0));
        }
    }
}

然后,如果你像这样装饰你的动作:

[UnderscoreToDash("on_show", "grid_colour")]
public JsonResult GetData()

它进行适当的“修复”。

PS 当 Resharper 将您的代码更改为 Linq 时,那令人敬畏的时刻......

_fixes.Aggregate(s, (current, fix) => current.Replace(fix, fix.Replace('_', '-')))
于 2012-08-24T15:05:42.517 回答