简体   繁体   中英

how to properly send JSON via ajax to c# [WebMethod]?

I want to send a JSON string via ajax to [WebMethod] . My JSON values contain double quotation marks ( " ). In js, I create an object and convert it to JSON with JSON.stringify(my_object) . Console shows properly formatted JSON (double quotes are masked with \\ ), jsonlint.com confirms it.

But the problem appears in [WebMethod] . After hours of debugging I found out that it ignores masked " and treats them as normal " . So my properly JSON-formatted string becomes not properly JSON-formatted string.

Is there a way to fix this? Changing my input string is not an option (I mustn't get rid of " ).

Here's some code:

ajax request:

$.ajax({
    type: 'POST',
    url: 'Test_Page.aspx/Test',
    data: "{json: '" + JSON.stringify(json_string) + "'}",
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (msg) {},
    error: function (msg) {}
});

web method:

[WebMethod]
public static string Test(string json) {
    return Newtonsoft.Json.JsonConvert.SerializeObject(Other_Function(json));
}

Try this:

$.ajax({
    type: 'POST',
    url: 'Test_Page.aspx/Test',
    data: JSON.stringify({json: json_string}),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (msg) {},
    error: function (msg) {}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM