将 json 字符串反序列化为对象数组,然后将其转换为字典?
Deserializing a json string to an object array and then cast it to Dictionary?
这是 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);
}
// 执行此操作时出现异常 saying cannot cast object m_receiptList[i] to 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);
}
这是 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);
}
// 执行此操作时出现异常 saying cannot cast object m_receiptList[i] to 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);
}