How to remove escape characters from a JSON String

六眼飞鱼酱① 提交于 2019-12-23 10:28:35

问题


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

回答1:


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);


来源:https://stackoverflow.com/questions/25979508/how-to-remove-escape-characters-from-a-json-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!