栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

MVC3 JSON序列化:如何控制属性名称?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MVC3 JSON序列化:如何控制属性名称?

我通过使用此问题答案中提供的技术解决了这个问题:

这是我上的课:

/// <summary>/// Similiar to <see cref="JsonResult"/>, with/// the exception that the <see cref="DataContract"/> attributes are/// respected./// </summary>/// <remarks>/// based on the excellent stackoverflow answer:/// https://stackoverflow.com/a/263416/1039947/// </remarks>public class JsonDataContractActionResult : ActionResult{    /// <summary>    /// Initializes a new instance of the class.    /// </summary>    /// <param name="data">Data to parse.</param>    public JsonDataContractActionResult(Object data)    {        Data = data;    }    /// <summary>    /// Gets or sets the data.    /// </summary>    public Object Data { get; private set; }    /// <summary>    /// Enables processing of the result of an action method by a     /// custom type that inherits from the ActionResult class.     /// </summary>    /// <param name="context">The controller context.</param>    public override void ExecuteResult(ControllerContext context)    {        if (context == null) throw new ArgumentNullException("context");        var serializer = new DataContractJsonSerializer(Data.GetType());        string output;        using (var ms = new MemoryStream())        { serializer.WriteObject(ms, Data); output = Encoding.UTF8.GetString(ms.ToArray());        }        context.HttpContext.Response.ContentType = "application/json";        context.HttpContext.Response.Write(output);    }}

用法:

    public ActionResult TestFunction()    {        var testObject = new TestClass();        return new JsonDataContractActionResult(testObject);    }

我还必须修改初始类:

// -- The DataContract property was added --[DataContract]public class JsonTreeNode{    [DataMember(Name = "title")]    public string Title { get; set; }    [DataMember(Name = "isFolder")]    public bool IsFolder { get; set; }    [DataMember(Name = "key")]    public string Key { get; set; }    [DataMember(Name = "children")]    public IEnumerable<JsonTreeNode> Children { get; set; }    [DataMember(Name = "select")]    public bool SelectedonInit { get; set; }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636748.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号