首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScriptConverter、ExpandoObject和动态类型

JavaScriptConverter、ExpandoObject和动态类型
EN

Stack Overflow用户
提问于 2014-03-11 15:28:06
回答 1查看 490关注 0票数 0

我有一个小小的考试课,像这样:

代码语言:javascript
复制
public class Command
{
    public dynamic MyData { get; set; }
}

作为dynamic MyData,我想使用ExpandoObject,所以我可以这样做:

代码语言:javascript
复制
Command cmd = new Command();
cmd.MyData = new ExpandoObject();
cmd.MyData.SomeStuff = 4;
cmd.MyData.SomeOtherStuff = "hi";

我正在尝试从json序列化到/反序列化。为了做到这一点,我使用了JavaScriptSerializer

我希望上面的示例对象序列化为:

代码语言:javascript
复制
{
    MyData : {
        SomeStuff : 4,
        SomeOtherStuff : "hi"
    }
}

为此,我需要一个JavaScriptConverter (取自本网站):

代码语言:javascript
复制
public class ExpandoJsonConverter : JavaScriptConverter
{
    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        return dictionary.ToExpando();
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        var result = new Dictionary<string, object>();
        var dictionary = obj as IDictionary<string, object>;
        foreach (var item in dictionary)
            result.Add(item.Key, item.Value);
        return result;
    }

    public override IEnumerable<Type> SupportedTypes
    {
        get
        {
            return new ReadOnlyCollection<Type>(new Type[] { typeof(ExpandoObject) });
        }
    }
}

public static class IDictionaryExtensions {
    /// <summary>
    /// Extension method that turns a dictionary of string and object to an ExpandoObject
    /// Snagged from http://theburningmonk.com/2011/05/idictionarystring-object-to-expandoobject-extension-method/
    /// </summary>
    public static ExpandoObject ToExpando(this IDictionary<string, object> dictionary) {
        var expando = new ExpandoObject();
        var expandoDic = (IDictionary<string, object>)expando;

        // go through the items in the dictionary and copy over the key value pairs)
        foreach (var kvp in dictionary) {
            // if the value can also be turned into an ExpandoObject, then do it!
            if (kvp.Value is IDictionary<string, object>) {
                var expandoValue = ((IDictionary<string, object>)kvp.Value).ToExpando();
                expandoDic.Add(kvp.Key, expandoValue);
            }
            else if (kvp.Value is ICollection) {
                // iterate through the collection and convert any strin-object dictionaries
                // along the way into expando objects
                var itemList = new List<object>();
                foreach (var item in (ICollection)kvp.Value) {
                    if (item is IDictionary<string, object>) {
                        var expandoItem = ((IDictionary<string, object>)item).ToExpando();
                        itemList.Add(expandoItem);
                    }
                    else {
                        itemList.Add(item);
                    }
                }

                expandoDic.Add(kvp.Key, itemList);
            }
            else {
                expandoDic.Add(kvp);
            }
        }

        return expando;
    }
}

现在,这可以很好地用于序列化,但是反序列化有以下问题:

  • 因为MyData是一个dynamic对象,而且ExpandoJsonConverter需要ExpandoObject,所以反序列化到MyData的数据是IDictionary<string, object>类型的。
  • 如果我将dynamic MyData更改为ExpandoObject MyData,我将无法说出cmd.MyData.SomeStuff = 4;,编译器将告诉我"ExpandoObject没有名为SomeStuff的属性“。
  • 最后,我可以将dynamic添加到受支持的ExpandoJsonConverter类型列表中,等等,您不能做typeof(dynamic)

有没有人知道一个巧妙的解决办法?我真的很喜欢这个功能,但是我不能使用像Newtonsoft这样的第三方序列化库。谢谢。

EN

回答 1

Stack Overflow用户

发布于 2018-03-14 14:59:24

反序列化为ExpandoObject,但声明变量dynamic,即您需要的是dynamic d = js.Deserialize<ExpandoObject>(json)

代码语言:javascript
复制
string json = @"{
    MyData : {
        SomeStuff : 4,
        SomeOtherStuff : ""hi""
    }
}";

var js = new JavaScriptSerializer();
js.RegisterConverters(new[] { new ExpandoJsonConverter() });    
dynamic d = js.Deserialize<ExpandoObject>(json);    
Console.WriteLine(d.MyData.SomeOtherStuff);

输出:

如果您需要一个Command对象,只需手动构造一个,并注入从序列化程序返回的dynamic对象:

代码语言:javascript
复制
var cmd = new Command { MyData = d };
Console.WriteLine(cmd.MyData.SomeStuff);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22330114

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档