[英]Deserializing a json string to an object array and then cast it to Dictionary?
This is the json string 这是json字符串
[{"ProductIdentifier":"{test:'some data'}","validationCompleted":0}]
I am trying to deserialize an object into an object array which works fine but when i am trying to cast it back to an dictionary i am getting an exception can anyone please help me with this thank you. 我试图将一个对象反序列化为一个可以正常工作的对象数组,但是当我尝试将其转换回字典时,我遇到了异常,有人可以帮助我吗,谢谢。
m_receiptsList is an object[]
m_receiptsList = JsonConvert.DeserializeObject<object[]>(pastJsonString,
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All});
for(int i=0; i<m_receiptsList.Length; i++)
{
Dictionary<string, object> receiptItem = (Dictionary<string, object>)m_receiptsList[i];
bool breceipt = receiptItem["validationCompleted"].Equals(0);
}
// exception while doing this saying cannot cast object m_receiptList[i] to dictionary. //例外,无法将对象m_receiptList [i]转换为字典。
If you want Json.NET to deserialize your JSON as an array of dictionaries, you need to tell it to do so: 如果您希望Json.NET将JSON反序列化为字典数组,则需要告诉它这样做:
object[] m_receiptsList;
m_receiptsList = JsonConvert.DeserializeObject<Dictionary<string, object>[]>(pastJsonString, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
Incidentally, setting TypeNameHandling = TypeNameHandling.All
isn't going to help you because your JSON sample has no type information. 顺便说一句,设置TypeNameHandling = TypeNameHandling.All
对您没有帮助,因为您的JSON示例没有类型信息。 If it did, there would be a property "$type"
at the beginning of your object(s). 如果是这样,则对象的开头将有一个属性"$type"
。
Also, JSON.Net will convert a JSON integer into a long
unless told otherwise, so you would need to do: 另外,除非另行说明,否则JSON.Net会将JSON整数转换为long
,因此您需要执行以下操作:
foreach (IDictionary<string, object> dict in m_receiptsList)
{
bool breceipt = dict["validationCompleted"].Equals((long)0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.