2017-05-04 128 views
0

我試圖反序列化JSON字符串,但我得到一個錯誤:用雙引號JSON序列化問題

var response = jss.Deserialize<Dictionary<string,string>>(responseValue); 

我得到了一個錯誤:

Type 'System.String' is not supported for deserialization of an array.

我認爲該錯誤會固定如果我改變\"'

這是字符串

"{\"data\":[],\"error\":1,\"error_msg\":\"could not find associated database\",\"message\":\"Please check sr_no that you have sent\"}"

我希望它這樣

"{'data':[],'error':1,'error_msg':'could not find associated database','message':'Please check sr_no that you have sent'}"

我曾嘗試使用這一功能如下但對我來說

responseValue.Replace("\"","'"); 
+1

你_sure_這串是什麼?它看起來只是它的調試器表示。另外,它看起來像是JSON,爲什麼要通過奇怪的字符串操作(特別是使它成爲_invalid_ JSON的字符串),而不是僅僅將它視爲JSON? –

+1

您的代碼有效https://dotnetfiddle.net/nwqUqM – fubo

+0

是的,它是一個調試器代表@JamesThorpe。實際發生的是我反序列化josn使用var response = jss.Deserialize >(responseValue);但是我得到一個錯誤,「類型'System.String'不支持數組的反序列化。」 – SaMeEr

回答

4

如果你期待在同一個變量的變化沒有工作那麼你需要再次設置它返回的結果。

responseValue = responseValue.Replace(@"\"","'"); 
+1

這應該是'.Replace(@「\」「」,「'」)', 。替換(@「」「」,「'」)或'.Replace(「\」「,」'「)'。當前的代碼不能編譯。 – Kobi

+0

替換引號字符不會修復任何Json反序列化錯誤。它可以*導致*他們雖然,如果字符串包含嵌入單引號 –

+0

同意,但問題將採取面值。 OP會從這個答案中得到他所需要的。它如何適合更大的圖景需要由他來處理。 –

0

試試這個:

String s = "{\"data\":[],\"error\":1,\"error_msg\":\"could not find associated database\",\"message\":\"Please check sr_no that you have sent\"}"; 

s= s.Replace("\"", "'"); 
0
string responseValue = "{\"data\":[],\"error\":1,\"error_msg\":\"could not find associated database\",\"message\":\"Please check sr_no that you have sent\"}"; 
Console.WriteLine(responseValue.Replace("\"", "'")); 

Check the output

如果您想返回該值,然後將其保存在一個變量,並返回該變量。希望我的回答對你有幫助。如果下面有任何評論。

0

錯誤消息解釋了這個問題:您試圖將包含數組屬性的字符串反序列化爲字符串字典。您不能將數組放入字符串中,因此Type 'System.String' is not supported for deserialization of an array.

具體來說,data屬性是一個空數組:

'data':[] 

這有什麼好做的引號字符。 JSON可以很好地處理單字符或雙字符。

您需要提供適合反序列化的類型。你可以反序列化屬性objectdynamic或創建一個JSON的文本匹配類,如:

var response = jss.Deserialize<Dictionary<string,object>>(responseValue); 

或者:

class MyError 
{ 
    public string[] data{get;set;} 
    public string error_msg {get;set;} 
    public string message {get;set;} 
} 

var response = jss.Deserialize<MyError>(responseValue);