问题描述
我需要的JavaScript对象传递给ASP.NET MVC和我正在考虑做这样的:
VAR P = {帐户:'123',页:'项'};
VAR消息=逃生(p.toSource());
//传递消息的操作方法
这会产生这样的事情(为转义可读性):
({账:123,页:项})
和ASP.NET MVC中我试图反序列化和失败。
首先,DataContractJsonSerializer在抱怨括号,没有异议,才通过删除:
{账:123,页:项}
然后,它抱怨一个,而不是,所以我试图用它来序列化datacontract,并得到了:
{账:123,页:项}
所以,问题是,我可以在ASP.NET MVC的东西,这将与JavaScript的toSource格式的工作,还是我从头错干什么呢?
The DataContractJsonSerializer
class is pretty strict in terms of JSON format and it adheres to the specification. For example:
{account:"123", page:"item"}
is invalid JSON according to the specification. You must put double quotes around property names. You could use JSON.stringify
in order to produce valid JSON:
var p = { account:'123', page:'item' };
var message = JSON.stringify(p);
which will produce {"account":"123","page":"item"}
which is now valid JSON. The JSON.stringify
function is natively built into modern browsers and if you want to support legacy browsers you could include json2.js into your page.
This being said, you could use the less strict JavaScriptSerializer class, or Json.NET which will accept your invalid JSON string:
public class MyModel
{
public string Account { get; set; }
public string Page { get; set; }
}
class Program
{
static void Main()
{
var json = "{account:\"123\", page:\"item\"}";
var serializer = new JavaScriptSerializer();
var model = serializer.Deserialize<MyModel>(json);
Console.WriteLine("account = {0}, page = {1}", model.Account, model.Page);
}
}
And this being said I don't know why you are deserializing manually the JSON instead of relying on the built in JsonValueProviderFactory:
[HttpPost]
public ActionResult MyAction(MyModel model)
{
...
}
and to invoke from javascript using AJAX:
$.ajax({
url: '@Url.Action("MyAction", "Home")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ account: "123", page: "item" }),
success: function(result) {
// TODO: process the results
}
});
See, now you now longer have to worry about any manual serialization/deserialization. Everything is handled by the framework for you.
这篇关于为什么DataContractJsonSerializer和toSource产生不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!