如果:
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 字符串了。