2015-08-18 38 views
0

我想从包含文件路径值的Web API返回的Json数组中创建一个字典。我在这里提取了一个示例NewtonSoft JsonConverter和斜杠字符

JsonConvert.DeserializeObject<Dictionary<string, string>>("[{'Path':'\6\6553_20140729_134527059.mp3'}]") 

各种组合会产生以下错误。只有一种方法可行,我很想知道为什么。如果有人能帮助..非常感谢

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. 
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. 
Path '', line 1, position 1 

下抛出上述错误

//Escape with double slash 
JsonConvert.DeserializeObject<Dictionary<string, string>>("[{'Path':'\\6\\6553_20140729_134527059.mp3'}]") 

//Escape with quadruple slash 
JsonConvert.DeserializeObject<Dictionary<string, string>>("[{'Path':'\\\\6\\\\6553_20140729_134527059.mp3'}]") 

//Multiple Json Objects in array 
JsonConvert.DeserializeObject<Dictionary<string, string>>("[{'Path':'\\6\\6553_20140729_134527059.mp3'},{'Path':'\\6\\6553_20140729_134527059.mp3'}]") 

//Double slash, single Json object 
JsonConvert.DeserializeObject<Dictionary<string, string>>("{'Path':'\\6\\6553_20140729_134527059.mp3'}") 

这是工作

//Quadruple slash, single object 
    JsonConvert.DeserializeObject<Dictionary<string, string>>("{'Path':'\\\\6\\\\6553_20140729_134527059.mp3'}") 

就像我刚才所说,任何帮助将唯一非常感谢

所有的测试在视觉工作室完成快速手表

+0

看到错误信息**'不能反序列化当前的JSON数组(例如[1,2,3])到类型'System.Collections.Generic.Dictionary'2 [System.String,System.String]'* *你的json是数组/列表。尝试反序列化List >' – Eser

回答

0

当JSON以“[”开头时,表示它代表列表/数组,因此解串器期望有某种列表作为参数,您的情况为 List<Dictionary<string, string>>