ExpandoObject对象JSON序列化概述2015-06-05如果: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"};});}