Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to translate bytes [...] at index ... from specified code page to Unicode when adding to index

I am using Newtonsoft.Json to create the JSON to update add items to an index, but I get the following error when I POST the request:

{"error":{"code":"","message":"The request is invalid.","innererror":{"message":"parameters : Unable to translate bytes [E3] at index 752 from specified code page to Unicode.\r\n","type":"","stacktrace":""}}}

I know the error occurs with some non letter characters in some of the strings in the data that I am serializing. The string data comes from SQL, so I'm guessing something is going on to do with encoding that I cannot figure out.

When I inspect the JSON string, and put it in manually construct a request with the same data in Fiddler it all works fine.

Does anyone have any idea what might be the problem, and how I can work around it?

like image 595
mikeyb Avatar asked Feb 17 '15 10:02

mikeyb


1 Answers

I found my own solution after a bit more digging.

Adding "StringEscapeHandling.EscapeNonAscii" to the serialization options solves the problem:

jsonSettings = new JsonSerializerSettings
{
    Formatting = Newtonsoft.Json.Formatting.Indented,
    ContractResolver = new CamelCasePropertyNamesContractResolver(),
    DateTimeZoneHandling = DateTimeZoneHandling.Utc,
    StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
};
like image 172
mikeyb Avatar answered Sep 23 '22 10:09

mikeyb