反序列化JSON来字典,DataContractJsonSerializer [英] Deserialize JSON to Dictionary with DataContractJsonSerializer

查看:335
本文介绍了反序列化JSON来字典,DataContractJsonSerializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下JSON结果INT响应:

I receive the following JSON result int the response:

{"result": { "":-41.41, "ABC":0.07, "XYZ":0.00, "Test":0.00 }}

我有prepared以下类deserializating:

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 结果属性最终与具有零项反序列化。 (也没有宣布何时上班结果词典&LT;字符串,小数&GT;

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

推荐答案

请参阅此 SO回答

根据您的JSON定义DataContract。

Define the DataContract according to your JSON.

[DataContract]
public class CustomObject
{
    [DataMember(Name = "Name")]
    public string Name { get; set; }

    [DataMember(Name = "Age")]
    public string Age { get; set; }

    [DataMember(Name = "Parent")]
    public Dictionary<string, object> Parent { get; set; }
}

使用的DataContract类,而反序列化。

Use the DataContract class while deserialization.

using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
    DataContractJsonSerializerSettings settings = 
            new DataContractJsonSerializerSettings();
    settings.UseSimpleDictionaryFormat = true;

    DataContractJsonSerializer serializer = 
            new DataContractJsonSerializer(typeof(CustomObject), settings);

    CustomObject results = (CustomObject)serializer.ReadObject(ms);
    Dictionary<string, object> parent = results.Parent;
}

这篇关于反序列化JSON来字典,DataContractJsonSerializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆