How to remove escape characters from a JSON String
27,002
After switching to use JavaScriptSerializer()
to deserialize JSON string , I realized that I have an int
type property
in my object for a decimal value in the JSON string. I changed int
to double
, and this solved my problem. Both JsonConvert.DeserializeObject<>
and JavaScriptSerializer()
handle escape character. There's no need to remove escape character.
I replaced the following codes:
jsonString = jsonString.Replace(@"\", " ");
SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);
return obj;
With:
return new JavaScriptSerializer().Deserialize<SearchObj.RootObject>(jsonString);
Author by
Sai Wai Maung
Updated on November 06, 2020Comments
-
Sai Wai Maung over 3 years
I called a REST API with the following JSON string returned:
"{\"profile\":[{\"name\":\"city\",\"rowCount\":1,\"location\": ............
I tried to remove escape character with the following code before I deserialize it:
jsonString = jsonString.Replace(@"\", " ");
But then when I deserialize it, it throws an
input string was not in a correct format
:SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);
The following is the complete code:
public static SearchRootObject obj() { String url = Glare.searchUrl; string jsonString = ""; // Create the web request HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; // Get response var response = request.GetResponse(); Stream receiveStream = response.GetResponseStream(); // Pipes the stream to a higher level stream reader with the required encoding format. StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); jsonString = jsonString + readStream.ReadToEnd(); jsonString = jsonString.Replace(@"\", " "); // A C# object representation of deserialized JSON string SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString); return obj; }