2014-09-22 56 views
3

刪除轉義字符我叫具有以下JSON字符串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); 

在F ollowing是完整的代碼:

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

能否請您發佈包含您遇到問題的確切JSON和您試圖反序列化的類的完整示例?另外,你爲什麼要刪除「\」字符? – 2014-09-23 12:51:15

+0

@AndrewWhitaker,我解決了這個問題,我發佈瞭解決方案作爲答案。 – 2014-09-23 13:45:45

回答

1

切換使用JavaScriptSerializer()反序列化JSON字符串後,我意識到,我在我的對象的intproperty在JSON字符串十進制值。我將int更改爲double,這解決了我的問題。 JsonConvert.DeserializeObject<>JavaScriptSerializer()都處理轉義字符。沒有必要刪除轉義字符。 我換成如下代碼:

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

有了:

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