asp.net - 从 asmx Web 方法中的 .NET 序列化字符串向 JSON 对象的根属性添加额外属性

标签 asp.net ajax json web-services asmx

假设我们正在序列化“Thing”类的 .NET 对象。当代理收到 JSON 响应时,我们的 JSON 对象的根属性是“d”。有没有办法在 asmx Web 方法中将属性添加到根属性,或将同级属性添加到来自 ASP.NET 的 JSON 对象?现在,我有一个 hack.. 我将该值作为额外参数放入 JSON 对象中的每个“Thing”对象中。

事物类和 Web 服务 ASP.NET 代码:

namespace Web.Controls.ThingList
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class ThingListService : System.Web.Services.WebService
    {
        [Serializable]
        public class Thing
        {
            public string id;
            public string name;
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false, XmlSerializeString = false)]
        public List<Thing> GetThingList(string start, string limit)  //
        {
            return GetList("Thing", start, limit);
        }

    }
}

JSON 对象:

{
    "d": [{
        "__type": "Web.Controls.ThingList.ThingListService+Thing",
        "id": "1",
        "name": "ONE"
    }, {
        "__type": "Web.Controls.ThingList.ThingListService+Thing",
        "id": "2",
        "name": "TWO"
    }]
}

最佳答案

这是我解决问题的方法:

    reader: {
        type: 'json',
        model: 'Thing',
        totalProperty: 'd.recordCount',
        idProperty: 'id',
        root: 'd.resultSet'
    },


[Serializable]
public class ProxyResponse
{
    public string recordCount;
    public List<Thing> resultSet;
}

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false, XmlSerializeString = false)]
public ProxyResponse GetThingList(string start, string limit)  //
{
    ProxyResponse response = new ProxyResponse();

    List<Thing> list = GetList("Thing", start, limit);

    response.recordCount = list.Count.ToString();
    response.resultSet = list;

    return response;
}

关于asp.net - 从 asmx Web 方法中的 .NET 序列化字符串向 JSON 对象的根属性添加额外属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12574834/

相关文章:

javascript - 从 json 在 javascript 中创建动态多维关联数组

android - Android ListView 中的 JSONArray

javascript - jQuery AJAX 从不运行成功函数

css - 在 asp 向导上更改事件步骤标题颜色

c# - .Net Forms 身份验证是否需要 session ?

asp.net - 将QueryString附加到asp.net核心 anchor 帮助器标签中的href

javascript - 如何使用 php 和 ajax 创建按位置过滤(使用复选框)引擎

javascript - 从页面底部刷新时无限滚动触发两次

ios - 来自 json 错误的数据类型 application/x-www-form-urlencoded

javascript - 使用 javascript 和 jquery 计算 gridview 单元格总数时出现错误