JSON 序列化,返回带有破折号的键?
我想从我的控制器返回 JSON,该控制器是从匿名类型生成的,并且键名称中包含破折号。这可能吗?
因此,如果我有这个:
public ActionResult GetJSONData() {
var data = new { DataModifiedDate = myDate.ToShortDateString() };
return Json(data);
}
在客户端,我希望它像这样序列化:
{ "data-modified-date" : "3/17/2011" }
我想要这个的原因是这个 Json 数据最终将成为 DOM 节点上的属性,并且我想玩得很好并使用新的 HTML5 数据属性。我可以返回 {modifieddate: "3/17/2011" }
并以这种方式使用它,但如果我可以变得更符合我想要的标准。
据我所知,如果我编写自己的 JsonResult
类,该类在非匿名类型上使用 WCF JSON Serializer,我可以使用 DataMemberAttribute
来完成此操作。但对于这样一个简单的愿望来说,这是很大的开销。
我也可以让客户端在收到数据后为我按摩密钥,但我也希望避免这种情况。总而言之,我宁愿不遵循标准,也不愿遵循这些解决方法。
I would like to return JSON from my controller which was generated from an anonymous type and contains dashes in the key names. Is this possible?
So if I have this:
public ActionResult GetJSONData() {
var data = new { DataModifiedDate = myDate.ToShortDateString() };
return Json(data);
}
On the client side I would like it to arrive serialized like this:
{ "data-modified-date" : "3/17/2011" }
My reason for wanting this is this Json data will ultimately become attributes on a DOM node, and I want to play nice and use the new HTML5 data attributes. I can just return { modifieddate: "3/17/2011" }
and use it this way, but if I can become that little bit more conforming to standards I'd like to be.
I understand if I write my own JsonResult
class that uses the WCF JSON Serializer on a non anonymous type, I can use theDataMemberAttribute
to accomplish this. But that's a lot of overhead for such a simple desire.
I could also have the client massage the keys for me once it receives the data, but I'm hoping to avoid that too. All in all I'd rather just not follow standards than either of these workarounds.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 Json.NET 并完全控制属性名称:
显然,这段代码迫切需要通过引入来改进自定义操作结果:
然后:
You could use Json.NET and have full control over property names:
Obviously this code is screaming to be improved by introducing a custom action result:
and then:
我发现 JsonResult 使用的 JavaScriptSerializer 对于字典有一个特殊情况。因此,如果您这样做:
那么生成的 JSON 就是所需的格式。
I found the JavaScriptSerializer that JsonResult uses has a special case for Dictionaries. So if you just do:
Then the resulting JSON is in the desired format.