JsonConvert.DeserializeObject special characters Unterminated string. Expected delimiter:
Solution 1
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.
Solution 2
I have got the same error a few times. I have updated my web.config with greater max lengths to ensure no truncating.
<httpRuntime maxQueryStringLength="2097151" maxUrlLength="2097151" />
<security>
<requestFiltering>
<requestLimits maxQueryString="2097151" maxUrl="2097151" />
</requestFiltering>
</security>
The encodeURIComponent() function encodes a URI component.
This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #
This has now been added to my ajax requests:
$.ajax("URL", {
type: "POST",
cache: false,
data: { a: encodeURIComponent(jsonData), b: userID }
})
user3272686
Updated on June 04, 2022Comments
-
user3272686 almost 2 years
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.
-
user3272686 about 10 yearsCan you give me an example?
-
user3272686 about 10 yearsI found an answer to my own question: escape(ko.toJSON(theModel)) All I need is the escape function and it works great.
-
dmikester1 over 7 years??, C# has no idea what "escape" is
-
tyler_mitchell about 7 yearsthis is a javascript function which has been deprecated (v1.5) see my answer for current answer. c# version of this would be Uri.UnescapeDataString()
-
autopilot almost 5 yearsI had the same problem and I have found the problem was because of the special character @. The encodeURIComponent() function did the trick.
-
StevenSiebert over 2 yearsThis does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question.