2017-04-05 57 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