如果:
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" }; }); }
返回栏目页:http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索new
, return
, dictionary
, public
, serializer
javascriptserializer
expandoobject json、jsonobject序列化、jsonobject 反序列化、expandoobject、c expandoobject,以便于您获取更多的相关知识。