2017-03-01 171 views
1

在此處提供了一些解決方案之後,我選擇了使用NewtonSoft。但我無法將JSON轉換爲類對象。我認爲,json(或字符串)以不正確的格式傳遞給方法。如何將JSON類似字符串轉換爲C#對象

類:

public class EmailAPIResult 
{ 
    public string Status { get; set; } 
} 

方法:

//....code 
using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
{ 
    string result = streamReader.ReadToEnd(); 
    //when hovered on "result", the value is "\"{\\\"Status\\\":\\\"Success\\\"}\"" 
    //For Text Visualizer, the value is "{\"Status\":\"Success\"}" 
    //And for JSON Visualizer, the value is [JSON]:"{"Status":"Success"}" 

    EmailAPIResult earesult = JsonConvert.DeserializeObject<EmailAPIResult>(result);  
    //ERROR : Error converting value "{"Status":"Success"}" to type 'EmailAPIResult'. 
} 

下面的代碼工作:

using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
    { 
     string good = "{\"Status\":\"Success\"}"; 
     //when hovered on "good", the value is "{\"Status\":\"Success\"}" 
     //For Text Visualizer, the value is {"Status":"Success"} 
     //And for JSON Visualizer, the value is 
     // [JSON] 
     //  Status:"Success" 

     EmailAPIResult earesult = JsonConvert.DeserializeObject<EmailAPIResult>(good); //successful 
    } 

我應該如何格式化 「結果」,讓我代碼有效。

+0

http://json2csharp.com/ –

+0

你甚至不寫如何你的JSON文件看起來像?!? –

+0

也許你的'httpResponse'爲空 –

回答

1

雖然這是真的,你可以修復你的字符串,就像m.rogalski建議,我會推薦而不是來做到這一點。

正如你說:

的 「結果」 徘徊時,該值是 「\」{\\\ 「狀態\\\」:\\\ 「成功\\\」} \」 「

我建議檢查它來自哪裏。什麼是你的後端實現?看起來好像您的HTTP答案的JSON結果實際上不是JSON,而是完全轉義的JSON字符串。 如果您可以控制後端發生的事情,那麼您應該真正修復它,因爲每次嘗試將客戶端寫入HTTP服務時都會出現類似問題。

無論如何,如果希望速戰速決,嘗試之一:

result = result.Replace(@"\\", @"\").Replace(@"\""", "\"").Trim('\"'); 

來電來Replace與轉義替換原有的轉義字符。 Trim修剪前導和尾隨引號。

+0

這是正確的。 HTTP的結果實際上並不是JSON,我不能控制它。 – Qwerty

+0

太可惜了。然後快速修復就足夠了。 –

+0

我想避免做'if(result.Contains(「success」))'。非常感謝你。那工作!!。 – Qwerty

0

正如你在你的問題已經證明:

的 「結果」 徘徊時,該值是 「\」{\\ 「狀態\\」:\\ 「成功\\」} \ 「」

這意味着你的JSON字符串的起始和轉義字符"結束。

試圖擺脫這些像這樣的(例如):

string result = streamReader.ReadToEnd(); 
result = result.Substring(1); 
result = result.Substring(0, result.Length - 1); 

,這將給你喜歡"{\\\"Status\\\":\\\"Success\\\"}"

編輯值: 結果我已是無效的(我壞),因爲它包含另一個非轉義字符,它是\。你可以擺脫這種使用string.Replace方法:

result = result.Replace("\\", string.Empty); 

但這些替代品的缺點是,如果您的JSON將包含該字符,它會被空(\0)字符替換

// {"Status":"Some\Other status"} 
// would become 
// {"Status":"SomeOther status"} 
+0

它現在給出了一個不同的錯誤'無效的屬性標識符字符:\'。在懸停'result'時,值就是你所提到的。對於Text Visualizer,值爲'{\「Status \」:\「Success \」}',對於JSON可視化器,它表示string不是json格式。 – Qwerty

相關問題