2017-04-05 38 views
1

在將其標記爲重複項之前,具有相似名稱的其他問題與正則表達式相關,並且與我的問題不同。字符在傳遞到字典時沒有正確轉義

我有串

Principal = "{\"id\":\"number\"}" 

如果我沒有記錯這應該逃避{"id":"number"}

然而,當我將它傳遞給下面的方法

Dictionary<string, object> folder = new Dictionary<string, object>(); 
      folder.Add("Principal", Principal); 
      string json = JsonConvert.SerializeObject(folder); 
      Console.WriteLine(json); 

它返回的

{ 
"Principal":"{\"id\":\"number\"}" 
} 

理想我想它返回

{ 
"Principal":{"id":"number"} 
} 

爲什麼持有引號和轉義字符?我在這裏做錯了什麼?

回答

5

您的委託人是一個字符串,因此可以作爲一個字符串逃脫。

如果您想將其作爲JSON對象轉義,則它也需要成爲應用程序中的對象。

如果你還想反序列化或多次使用它,我建議在一個類中定義你的對象。如果沒有,你可以使用匿名對象:

Dictionary<string, object> folder = new Dictionary<string, object>(); 
folder.Add("Principal", new { id = "number" }); 
string json = JsonConvert.SerializeObject(folder); 
Console.WriteLine(json); 

/編輯:這裏是將其與非匿名類:

類定義:

class Principal 
{ 
    public string id { get; set; } 
} 

用法:

Dictionary<string, object> folder = new Dictionary<string, object>(); 
folder.Add("Principal", new Principal(){ id = "number" }); 
string json = JsonConvert.SerializeObject(folder); 
Console.WriteLine(json); 
+0

非常好,謝謝!我的代碼仍然無法工作,但這部分是感謝你! – Mitch

3

一個選項添加到@ Compufreak的answer

您撥打JsonConvert.SerializeObject()表示您已使用。如果您有需要包括原樣而不當容器被序列化的一些容器POCO逃逸預先序列化JSON文本字符串,就可以在JRaw對象包裹字符串:

folder.Add("Principal", new Newtonsoft.Json.Linq.JRaw(Principal)); 

JsonConvert.SerializeObject()也將隨之發出JSON字符串而不逃逸。當然,Principal字符串需要是有效的 JSON,否則最終的序列化會很糟糕。

樣品fiddle

相關問題