如何通过ajax将JSON正确发送到c#[WebMethod]

本文关键字:WebMethod ajax 何通过 JSON | 更新日期: 2023-09-27 18:00:26

我想通过ajax向[WebMethod]发送一个JSON字符串。我的JSON值包含双引号(")。在js中,我创建了一个对象,并使用JSON.stringify(my_object)将其转换为JSON。控制台显示格式正确的JSON(双引号用'屏蔽),jsonlint.com对此进行了确认

但问题出现在[WebMethod]中。经过几个小时的调试,我发现它忽略了屏蔽的",并将它们视为正常的"。因此,我的JSON格式的字符串变成了不正确的JSON格式字符串。

有办法解决这个问题吗?更改我的输入字符串不是一个选项(我不能去掉")。

这里有一些代码:

ajax请求:

$.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方法:

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

如何通过ajax将JSON正确发送到c#[WebMethod]

试试这个:

$.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) {}
});