How to remove escape characters from a JSON String

2019-06-23 22:40发布

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 correctt 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;
    }

1条回答
乱世女痞
2楼-- · 2019-06-23 23:15

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);
查看更多
登录 后发表回答