这是json字符串
[{"ProductIdentifier":"{test:'some data'}","validationCompleted":0}]
我正试图将一个对象反序列化为一个对象数组,这很好,但当我试图将其强制转换回字典时,我遇到了一个异常。有人能帮我吗?谢谢。
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);
}
//执行此操作时出现异常,表示无法将对象m_receiptList[i]强制转换为dictionary。
如果您希望Json.NET将Json反序列化为字典数组,您需要告诉它这样做:
object[] m_receiptsList;
m_receiptsList = JsonConvert.DeserializeObject<Dictionary<string, object>[]>(pastJsonString, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
顺便说一句,设置TypeNameHandling = TypeNameHandling.All
对您没有帮助,因为您的JSON示例没有类型信息。如果是,那么在对象的开头将有一个属性"$type"
。
此外,除非另有说明,否则JSON.Net将把JSON整数转换为long
,因此您需要执行以下操作:
foreach (IDictionary<string, object> dict in m_receiptsList)
{
bool breceipt = dict["validationCompleted"].Equals((long)0);
}