为什么DataContractJsonSerializer和toSource产生不同的结果? [英] Why DataContractJsonSerializer and toSource produces different results?

查看:90
本文介绍了为什么DataContractJsonSerializer和toSource产生不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的JavaScript对象传递给ASP.NET MVC和我正在考虑做这样的:

  VAR P = {帐户:'123',页:'项'};
VAR消息=逃生(p.toSource());
//传递消息的操作方法

这会产生这样的事情(为转义可读性):

 ({账:123,页:项})

和ASP.NET MVC中我试图反序列化和失败。
首先,DataContractJsonSerializer在抱怨括号,没有异议,才通过删除:

  {账:123,页:项}

然后,它抱怨一个,而不是,所以我试图用它来序列化datacontract,并得到了:

  {账:123,页:项}

所以,问题是,我可以在ASP.NET MVC的东西,这将与JavaScript的toSource格式的工作,还是我从头错干什么呢?


解决方案

  

所以,问题是,我可以在ASP.NET MVC的东西,将工作
  与JavaScript的toSource格式,还是我从头错干什么呢?


的<一个href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx\"相对=nofollow> DataContractJsonSerializer 类是pretty严格JSON格式条款,并坚持规范。例如:

  {账:123,页:项}

无效的JSON 根据规范。你必须将属性名称双引号。你可以使用 JSON.stringify 以产生有效的JSON:

  VAR P = {帐户:'123',页:'项'};
变种消息= JSON.stringify(对);

这将产生 {账:123,页:项} 这是目前有效的JSON。在 JSON.stringify 功能是本机内置于现代的浏览器,如果你想支持旧版浏览器,你可以包括的 json2.js 中到您的网页。

这就是说,你可以使用不太严格的<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx\"相对=nofollow>的JavaScriptSerializer 类或 Json.NET 这会接受你的无效的JSON字符串:

 公共类为MyModel
{
    公共字符串帐户{搞定;组; }
    公共字符串页{搞定;组; }
}类节目
{
    静态无效的主要()
    {
        VAR的json ={账:\\123 \\页:\\项\\};
        VAR串行=新的JavaScriptSerializer();
        VAR模型= serializer.Deserialize&LT;&为MyModel GT;(JSON);
        Console.WriteLine(账号= {0}页= {1},model.Account,model.Page);
    }
}

这是说,我不知道你为什么手动反序列化JSON而不是依靠内置的<一个href=\"http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx\"相对=nofollow> JsonValueProviderFactory :

  [HttpPost]
公众的ActionResult MyAction(为MyModel模型)
{
    ...
}

和从JavaScript使用AJAX调用:

  $。阿贾克斯({
    网址:'@ Url.Action(MyAction,家),
    输入:POST,
    的contentType:应用/ JSON,
    数据:JSON.stringify({账:123,页:项})
    成功:函数(结果){
        // TODO:处理结果
    }
});

看,现在你现在再也不用担心任何手动序列化/反序列化。一切都是由你的框架来处理。

I need to pass javascript object to ASP.NET MVC and I'm thinking do it like this:

var p = { account:'123', page:'item' }; 
var message = escape(p.toSource());
// pass message to action method

That produces something like this (unescaped for readability):

({account:"123", page:"item"})

And in ASP.NET MVC I'm trying to deserialize it and fail. First, DataContractJsonSerializer was complaining about parenthesis, no problem with that, removed before passing:

{account:"123", page:"item"}

Then it complained about a instead of ", so I've tried to serialize datacontract using it, and got:

{"account":"123", "page":"item"}

So, question is, can i use something in ASP.NET MVC, that would work with javascripts toSource format, or am I doing it from scratch wrong?

解决方案

So, question is, can i use something in ASP.NET MVC, that would work with javascripts toSource format, or am I doing it from scratch wrong?

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产生不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆