如何从JSON字符串中删除转义字符

时间:2014-09-22 17:07:56

标签: c#-4.0 asp.net-web-api json.net

我调用了一个REST API,返回了以下JSON字符串:

"{\"profile\":[{\"name\":\"city\",\"rowCount\":1,\"location\": ............

在我反序列化之前,我尝试使用以下代码删除转义字符:

 jsonString = jsonString.Replace(@"\", " ");

但是当我反序列化它时,它会抛出input string was not in a correctt format

SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);

以下是完整的代码:

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 个答案:

答案 0 :(得分:1)

切换到使用JavaScriptSerializer()反序列化JSON字符串后,我意识到我的对象中有一个int类型property,用于JSON字符串中的十进制值。我将int更改为double,这解决了我的问题。 JsonConvert.DeserializeObject<>JavaScriptSerializer()都处理转义字符。没有必要删除转义字符。 我替换了以下代码:

jsonString = jsonString.Replace(@"\", " ");        
SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);
return obj;

使用:

return new JavaScriptSerializer().Deserialize<SearchObj.RootObject>(jsonString);