我有以下 json 数据作为字符串
string data = "{\"STARTTIME\":\"12:00\",\"ENGINNEERSIGNATURE\":\"Engineer Signature .jpg\",\"OVERNIGHTS\":\"1\",\"SIGNOUT\":\"Yes\"}"
var dataOut = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
我需要将它转换为一个字典对象,但尝试时出现以下错误
Newtonsoft.Json.JsonSerializationException: Error converting value "{"STARTTIME":"12:00","ENGINNEERSIGNATURE":"Engineer Signature .jpg","OVERNIGHTS":"1","SIGNOUT":"Yes"}" to type 'System.Collections.Generic.Dictionary`2[System.String,System.String]'. Path '', line 1, position 119. ---> System.ArgumentException: Could not cast or convert from System.String to System.Collections.Generic.Dictionary`2[System.String,System.String].
at Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable (System.Object value, System.Type initialType, System.Type targetType) [0x00062] in <2781d1b198634655944cdefb18b3309b>:0
at Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast (System.Object initialValue, System.Globalization.CultureInfo culture, System.Type targetType) [0x00031] in <2781d1b198634655944cdefb18b3309b>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType (Newtonsoft.Json.JsonReader reader, System.Object value, System.Globalization.CultureInfo culture, Newtonsoft.Json.Serialization.JsonContract contract, System.Type targetType) [0x0008d] in <2781d1b198634655944cdefb18b3309b>:0
--- End of inner exception stack trace ---
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType (Newtonsoft.Json.JsonReader reader, System.Object value, System.Globalization.CultureInfo culture, Newtonsoft.Json.Serialization.JsonContract contract, System.Type targetType) [0x000bd] in <2781d1b198634655944cdefb18b3309b>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x000d7] in <2781d1b198634655944cdefb18b3309b>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) [0x0007a] in <2781d1b198634655944cdefb18b3309b>:0
我哪里错了
最佳答案
尝试使用Dictionary<string,object>
,这将允许 JSON 的值是任何对象类型。 Dictionary<string,string>
仅当 JSON 对象的所有值都是字符串类型时才有效。但如果有任何其他值,如数组或嵌套的 JSON 对象,它将失败。
关于c# - 转换 JSON 字符串时出现 JsonConvert.DeserializeObject 错误 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41870333/