Deserialize JSON to Dictionary with DataContractJs

2020-02-09 08:38发布

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; }
}

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>)

Is there a way to perform this with DataContractJsonSerializer?

1条回答
家丑人穷心不美
2楼-- · 2020-02-09 09:03

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 }] }

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.

查看更多
登录 后发表回答