Search code examples
c#jqueryasp.net-mvcjsonknockout.js

JsonConvert.DeserializeObject special characters Unterminated string. Expected delimiter:


For some reason, when I have a special character in my knockout model and convert it to a json object, the string ends where the special character is supposed to be and I get an error when deserializing it:

$.ajax({
    url: "/Admin/Forms/Convert",
    type: "post",
        //contentType: "application/json",
        dataType: "text",
        data: "modelData=" + ko.toJSON(theModel),
        success: function (data) {

            // window.open("/Admin/Forms/DisplayClient");
            var win = getFullWindow('/Admin/Forms/DisplayClient');
            win.open();
        },
        error: function (xhr, status, msg) { alert(msg); }
    });

When I get to this method:

public void Convert(string modelData)
{
    Form form = JsonConvert.DeserializeObject<Form>(modelData);
}

I get an error:

Unterminated string. Expected delimiter: ". Path 'Name', line 1, position 178.

Solution

  • If a JSON string contains special characters like double quotes ", backslashes \ or slashes /, they need to be escaped with backslashes \. There is no JSON parser that will be able to deal with a JSON string that isn't properly formatted in the first place.

    So you need to make sure that your theModel is formatted appropriately and according to JSON.org standards.