Asmx Web服务JSon响应没有考虑DataMember(Name =

时间:2010-08-16 10:01:38

标签: asp.net json

我无法在asmx Web服务中获得正确的json响应。数据结构使用DataContract和DataMember属性定义,但指定DataMember Name不会更改响应数据。你有什么主意吗?这里是代码(它是jqgrid的代码):

    /// <summary>
        /// a row of the jquery table
        /// </summary>
        [DataContract()]
        public class RowElement
        {
            /// <summary>
            /// an Id for each row
            /// </summary>
            [DataMember(Name = "id")]
            public string Id { get; set; }

            /// <summary>
            /// the table of cells
            /// </summary>
            [DataMember(Name = "cell")]
            public string[] Cell { get; set; }
        }

        /// <summary>
        /// the table for jquery
        /// </summary>
        [DataContract()]
        public class MainGrid
        {
            /// <summary>
            /// the number of pages
            /// </summary>
            [DataMember(Name = "total")]
            public string Total { get; set; }

            /// <summary>
            /// the num of the actual Page?
            /// </summary>
            [DataMember(Name = "page")]
            public string Page { get; set; }

            /// <summary>
            /// nb of elements in all the table
            /// </summary>
            [DataMember(Name = "records")]
            public string Records { get; set; }

            /// <summary>
            /// the list of Rows
            /// </summary>
            [DataMember(Name = "rows")]
            public RowElement[] Rows { get; set; }
        }



    /// <summary>
            /// method for jquery
            /// </summary>
            /// <param name="numRows">nb of Rows</param>
            /// <param name="Page">nb of Page</param>
            /// <param name="sortField">the column for the sort</param>
            /// <param name="sortOrder">the order of the sort</param>
            /// <param name="searchString">the filter if defined</param>
            /// <returns>the grid returned</returns>
            [WebMethod]
            [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
            ////int Page, int pageSize, string sortIndex, string sortDirection
            public MainGrid jQGridDataASMX(int? numRows, int? page, string sortField, string sortOrder, string searchString)
            {

    ...
MainGrid mg = new MainGrid();
return mg;    
    }

客户端数据仍为Id而非id。

2 个答案:

答案 0 :(得分:0)

我想我发现为什么它不起作用。这是因为ScriptMethod将使用JavascriptSerializer而不是DataContractJSonSerializer。所以我必须将这些服务迁移到wcf,但当我阅读http://msdn.microsoft.com/en-us/library/bb412168.aspx时,我看到的DataContractJSonSerializer并不像JSON那样友好,因为他们说...... 因此,如果有人有解决方案来做我试图用JavascriptSerializer做的事情,我很受欢迎。

答案 1 :(得分:0)

[DataContract][DataMember]是WCF的一部分。它们与ASMX Web服务无关。