ExpandoObject对象的JSON序列化

如果:

dynamic expando = new ExpandoObject();
d.SomeProp=SomeValueOrClass;

然后,我们在控制器中:

return new JsonResult(expando);

那么,我们的前台将会得到:

[{"Key":"SomeProp", "Value": SomeValueOrClass}]

而实际上,我们知道,JSON 格式的内容,应该是这样的:

{SomeProp: SomeValueOrClass}

于是乎,我们需要一个自定义的序列化器,它应该如下:

public class ExpandoJSONConverter : JavaScriptConverter
{
    public override IEnumerable<Type> SupportedTypes
    {
        get
        {
            return new ReadOnlyCollection<Type>(new Type[] { typeof(System.Dynamic.ExpandoObject) });
        }
    }

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        throw new NotImplementedException();
    }

    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 ContentResult GetSomeThing(string categores)
{
    return ControllProctector.Do1(() =>
        {

            …
            var serializer = new JavaScriptSerializer();
            serializer.RegisterConverters(new JavaScriptConverter[] { new ExpandoJSONConverter() });
            var json = serializer.Serialize(expando);
            return new ContentResult
            {
                Content = json,
                ContentType = "application/json"
            };
        });
}

我们的浏览器就能得到正确的 JSON 字符串了。

 

备注:其它的方法还有

一:

dynamic expando = new ExpandoObject();
expando.Blah = 42;
expando.Foo = "test";
...

var d = expando as IDictionary<string, object>;
d.Add("SomeProp", SomeValueOrClass);

// After you've added the properties you would like.
d = d.ToDictionary(x => x.Key, x => x.Value);
return new JsonResult(d);

二: JSON.NET

dynamic expando = new ExpandoObject();
expando.name = "John Smith";
expando.age = 30;

var json = JsonConvert.SerializeObject(expando);

三:Content-method:

public ActionResult Data()
{
    dynamic expando = new ExpandoObject();
    expando.name = "John Smith";
    expando.age = 30;

    var json = JsonConvert.SerializeObject(expando);

    return Content(json, "application/json");
}

参考:http://stackoverflow.com/questions/5156664/how-to-flatten-an-expandoobject-returned-via-jsonresult-in-asp-net-mvc

你可能感兴趣的:(object)