使用 DataContractJsonSerializer 将 JSON 反序列化为字典 [英] Deserialize JSON to Dictionary with DataContractJsonSerializer
问题描述
我在响应中收到以下 JSON 结果:
I receive the following JSON result int the response:
{"result": { "":-41.41, "ABC":0.07, "XYZ":0.00, "Test":0.00 }}
我准备了以下用于反序列化的类:
I've prepared the following class for deserializating:
[DataContract]
public sealed class RpcResponse
{
[DataMember(Name = "result")]
public List<KeyValuePair<string, decimal>> Result { get; set; }
}
然而,当我试图用 DataContractJsonSerializer
反序列化它时,Result
属性最终会得到零个条目.(在将 Result
声明为 Dictionary
时也不起作用)
However when I'm tring to deserialize it with DataContractJsonSerializer
the Result
property ends up with having zero entries. (Also doesn't work when declaring Result
as Dictionary<string, decimal>
)
有没有办法使用 DataContractJsonSerializer
执行此操作?
Is there a way to perform this with DataContractJsonSerializer
?
推荐答案
您的 JSON 字符串表示具有属性 Result 的对象,该对象本身是具有 4 个属性的对象:""、ABC、XYZ 和 Test.要使结果成为 KeyValuePairs 列表,JSON 将如下所示:
Your JSON string represents an object with a property Result that is itself an object with 4 properties: "", ABC, XYZ, and Test. For result to be a list of KeyValuePairs, the JSON would look like this:
{"result": [{ "":-41.41}, {"ABC":0.07}, {"XYZ":0.00}, {"Test":0.00 }] }
请注意,如果您在 Javascript 代码中使用关联数组,它将被序列化为具有属性值对的对象,而不是对象数组.如果这是 JSON 字符串的来源,您可能需要切换到在 JS 中使用普通索引数组来获取正确的 JSON.
Note that if you are using an associative array in Javascript code, that it is going to be serialized as an object with property-value pairs, not as an array of objects. If that is the source of the JSON string, you may need to switch to using an ordinary indexed array in your JS to get the proper JSON.
这篇关于使用 DataContractJsonSerializer 将 JSON 反序列化为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!