简体   繁体   English

为什么DataContractJsonSerializer和toSource产生不同的结果?

[英]Why DataContractJsonSerializer and toSource produces different results?

I need to pass javascript object to ASP.NET MVC and I'm thinking do it like this: 我需要将javascript对象传递给ASP.NET MVC,我想这样做:

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. 在ASP.NET MVC中,我试图反序列化它并失败。 First, DataContractJsonSerializer was complaining about parenthesis, no problem with that, removed before passing: 首先,DataContractJsonSerializer抱怨括号,没有问题,在传递之前删除:

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

Then it complained about a instead of ", so I've tried to serialize datacontract using it, and got: 然后它抱怨而不是“,所以我试图使用它来序列化datacontract,并得到:

{"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? 所以,问题是,我可以在ASP.NET MVC中使用某些东西,它可以使用javascripts toSource格式,还是我从头开始做错了?

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? 所以,问题是,我可以在ASP.NET MVC中使用某些东西,它可以使用javascripts toSource格式,还是我从头开始做错了?

The DataContractJsonSerializer class is pretty strict in terms of JSON format and it adheres to the specification. DataContractJsonSerializer类在JSON格式方面非常严格,并且符合规范。 For example: 例如:

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

is invalid JSON according to the specification. 根据规范是无效的JSON You must put double quotes around property names. 您必须在属性名称周围加上双引号。 You could use JSON.stringify in order to produce valid JSON: 您可以使用JSON.stringify来生成有效的JSON:

var p = { account:'123', page:'item' }; 
var message = JSON.stringify(p);

which will produce {"account":"123","page":"item"} which is now valid JSON. 这将产生{"account":"123","page":"item"} ,它现在是有效的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. JSON.stringify函数本身内置于现代浏览器中,如果您想支持旧版浏览器,可以在页面中包含json2.js

This being said, you could use the less strict JavaScriptSerializer class, or Json.NET which will accept your invalid JSON string: 话虽这么说,你可以使用不太严格的JavaScriptSerializer类,或者接受你的无效JSON字符串的Json.NET

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 : 这就是说我不知道​​为什么你手动反序列化JSON而不是依赖于内置的JsonValueProviderFactory

[HttpPost]
public ActionResult MyAction(MyModel model)
{
    ...
}

and to invoke from javascript using AJAX: 并使用AJAX从javascript调用:

$.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. 一切都由框架为您处理。

The .toSource() method does not return JSON. .toSource()方法不返回JSON。 In your case, the valid JSON representation of your object would be: 在您的情况下,对象的有效JSON表示将是:

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

The format that .toSource() returns is explained in the MDN documentation . .toSource()返回的格式在MDN文档中进行了说明

To serialize your objects in your JavaScript, I recommend using a third party library for the most compatibility. 要在JavaScript中序列化对象,我建议使用第三方库以获得最大的兼容性。 Specifically, you could use json2.js . 具体来说,您可以使用json2.js However, if you are using a modern browser, you could also use the .stringify() method of the new JSON object . 但是,如果您使用的是现代浏览器,则还可以使用新JSON对象.stringify()方法。 But, again, the most versatile approach is the third party library. 但是,最通用的方法是第三方库。

In case anybody needs it, I've done it like this: 如果有人需要它,我就是这样做的:

function getSource(o) { var r = [], t; for (var i in o) if (o.hasOwnProperty(i)) { t = i + "~~" + "'" + o[i] + "'"; r.push(t); }; return r.join(); }        

Notice, that it has several limitations/differences from original toSource(): 请注意,它与原始toSource()有几个限制/差异:

a) my model, that I'm passing is always flat, that means all properties are assumed as strings, if your model has complex properties, you need to change code to use recursion for complex properties. a)我传递的模型总是平坦的,这意味着所有属性都被假定为字符串,如果模型具有复杂属性,则需要更改代码以使用递归来表示复杂属性。
b) I'm using single quotes, while original toSource uses double quotes. b)我使用单引号,而原始的toSource使用双引号。
c) I'm replacing ":" to "~~", because even encoded it was breaking the url, so before serializing on server side, you need to do replace. c)我正在将“:”替换为“~~”,因为即使编码它也会破坏URL,因此在服务器端序列化之前,需要进行替换。
d) original toSource was returning result in closures, which i don't needed, so my function returns result without them. d)原始的toSource返回结果,我不需要闭包,所以我的函数返回没有它们的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 BinaryFormatter序列化产生不同的结果 - BinaryFormatter Serialize Produces Different Results DataContractJsonSerializer生成散列列​​表而不是散列 - DataContractJsonSerializer produces list of hashes instead of hash 字符串拆分产生的结果与预期不同 - String splitting produces different results than expected DataContractJsonSerializer和JsonConvert给出了不同的结果 - DataContractJsonSerializer and JsonConvert give different result 为什么 DateTimeOffset 的 DataContractJsonSerializer 和 Json.NET 序列化会产生不同的 json? - Why do DataContractJsonSerializer and Json.NET serialization of DateTimeOffset produce different json? Math.Round根据其运行位置产生不同的结果 - Math.Round produces different results depending on where it is run Range.Value在VBA和C#中产生不同的结果 - Range.Value produces different results in VBA and C# 存储过程产生从c#.net调用的不同结果 - Stored procedure produces different results calling from c# .net 为什么DataContractJsonSerializer跳过反序列化某些属性? - Why does DataContractJsonSerializer skip deserializing some properties? Xamarin.Android上具有TimeSpan的DataContractJsonSerializer有所不同 - DataContractJsonSerializer with TimeSpan is different on Xamarin.Android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM