我正在尝试反序列化我的JSON对象,并将其作为模型传递给我的视图。由于不知道模型会有什么属性,我已经读过我应该使用一个ExpandoObject。

这是我试过的:

public ActionResult Index()
{
    var myObj = new object();

    List<Dictionary<string, object>> container = new List<Dictionary<string, object>>()
    {
        new Dictionary<string, object> { { "Text", "Hello world" } }
    };
    JavaScriptSerializer json_serializer = new JavaScriptSerializer();
    myObj = json_serializer.DeserializeObject(json_serializer.Serialize(container));
    return View(myObj.ToExpando());
}

而且,在同一个命名空间中,我定义了这个类:

public static class Helpers
{
    public static ExpandoObject ToExpando(this object anonymousObject)
    {
        IDictionary<string, object> anonymousDictionary = new RouteValueDictionary(anonymousObject);
        IDictionary<string, object> expando = new ExpandoObject();
        foreach (var item in anonymousDictionary)
            expando.Add(item);
        return (ExpandoObject)expando;
    }
}

而且,在我看来,我有这个循环:

@foreach (var item in Model)
{
    @item.Text
}

当我运行,我得到这个错误:

'系统。收藏品。通用的。KeyValuePair'不 包含"文本"的定义

在调试时,模型似乎没有任何公共属性。当我深入查看私人成员时,我会看到我想要的数据。

为什么这些公共属性不能让我访问它们?

编辑: 在这里,您可以看到正在传递到我的视图的expando对象模型:

enter image description here

注:SyncRoot 属性似乎包含我的对象。

编辑: 这是反序列化的对象:

enter image description here

有帮助吗?

解决方案 2

The solution for me was to do something like this (using the ExpandoObjectConverter):

var myObj = new object();

List<Dictionary<string, object>> container = new List<Dictionary<string, object>>()
{
    new Dictionary<string, object> { { "Text", "Hello world" } }
};
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
var converter = new ExpandoObjectConverter();
var obj = JsonConvert.DeserializeObject<IEnumerable<ExpandoObject>>(json_serializer.Serialize(container), converter);

return View(obj);

However, this doesn't account for deeply nested JSON objects. I can probably create some sort of recursive method.

It's sad that the framework doesn't support such an obvious requirement; unless I am missing something.

其他提示

请注意 @item 被定义为 System.Collections.Generic.KeyValuePair 根据你的错误。

这意味着你有两个属性: 钥匙价值.

这里有两个可能的解决方案:

@foreach (var item in Model.Values)
{
    @item.Id
}

@foreach (var item in Model)
{
    @item.Value.Id
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top