How to remove escape characters from JSON string
I called the REST API with the following JSON string returned:
"{\"profile\":[{\"name\":\"city\",\"rowCount\":1,\"location\": ............
I tried to remove the escape character with the following code before I deserialize it:
jsonString = jsonString.Replace(@"\", " ");
But then when I deserialize it, it throws input string was not in a correctt format
:
SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);
Below 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;
}
source to share
After switching to using a JavaScriptSerializer()
JSON string to deserialize, I realized that I have a type int
property
in my object for a decimal value in a JSON string. I changed int
to double
and that solved my problem. Both characters JsonConvert.DeserializeObject<>
and JavaScriptSerializer()
are escaped. There is no need to remove the escape character. I replaced the following codes:
jsonString = jsonString.Replace(@"\", " ");
SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);
return obj;
FROM
return new JavaScriptSerializer().Deserialize<SearchObj.RootObject>(jsonString);
source to share