这是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]强制转换为字典。
答案 0 :(得分:1)
如果你希望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);
}