我正在构建一个使用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#代码中命名属性时不能使用破折号。
有没有办法克服这个问题?最好不需要声明一大堆类。
答案 0 :(得分: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编辑器编写;我可能会犯一些语法错误,但你明白了......)
答案 1 :(得分:0)
Craig的解决方案可能更好,但在此期间我实现了这个:
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()
它会做出相应的“修正”。
P.S。 Resharper将您的代码更改为Linq的那个令人敬畏的时刻...
_fixes.Aggregate(s, (current, fix) => current.Replace(fix, fix.Replace('_', '-')))