无法将dynamicJsonObject转换为Dictionary<;字符串,对象>

本文关键字:lt 字符串 gt 对象 Dictionary dynamicJsonObject 转换 | 更新日期: 2023-09-27 18:01:00

我正在使用dynamicJsonDeserializer来反序列化我的json,它运行得很好。

public class DynamicJsonObject : DynamicObject
{
    private IDictionary<string, object> Dictionary { get; set; }
    public DynamicJsonObject(IDictionary<string, object> dictionary)
    {
        this.Dictionary = dictionary;
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = this.Dictionary[binder.Name];
        if (result is IDictionary<string, object>)
        {
            result = new DynamicJsonObject(result as IDictionary<string, object>);
        }
        else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
        {
            result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
        }
        else if (result is ArrayList)
        {
            result = new List<object>((result as ArrayList).ToArray());
        }
        return this.Dictionary.ContainsKey(binder.Name);
    }
}
public class DynamicJsonConverter : JavaScriptConverter
{
    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        if (dictionary == null)
            throw new ArgumentNullException("dictionary");
        if (type == typeof(object))
        {
            return new DynamicJsonObject(dictionary);
        }
        return null;
    }
    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        throw new NotImplementedException();
    }
    public override IEnumerable<Type> SupportedTypes
    {
        get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); }
    }
}

为什么我不能将DynamicJsonObject转换为Dictionary,这样我就可以用它做一些事情了?

dynamic obj = serializer.Deserialize(jsonResponse, typeof(object));
Dictionary<string, object> test = new Dictionary<string, object>(dynamicObject.Dictionary); //cannot do this

无法将dynamicJsonObject转换为Dictionary<;字符串,对象>

通过公开Dictionary,我的问题很容易解决。