0

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));
}

1 Answer 1

3

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) {}
});
Sign up to request clarification or add additional context in comments.

2 Comments

almost, I had to stringify my json_string: data: JSON.stringify({json: JSON.stringify(json_string)}). Thanks!
No problem :) It's just the way you pass it. I think the result should be the same if you do it like this, for example: JSON.stringify({json: ' "test" '})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.