【问题标题】:Adding extra property to root property of JSON object from .NET Serialized string in asmx web method在 asmx Web 方法中从 .NET 序列化字符串向 JSON 对象的根属性添加额外属性
【发布时间】:2012-09-16 11:47:41
【问题描述】:

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

事物类和网络服务 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"
    }]
}

【问题讨论】:

  • 只是澄清一下,作为d的兄弟?不幸的是,我不这么认为。使用 d 包装响应是 .NET 3.5 中实现的安全功能。
  • 当然,没关系.. 我只是想将一个额外的值传递回 JSON 对象中的 JavaScript 代码
  • 所以我应该只用属性 List 和这个额外的属性创建一个全局响应类(序列化)吗?并通过它而不是 List?
  • 您可能需要构建自己的包装器:ThingWrapper,它拥有额外的属性以及Things 的列表。但这可能意味着要重写很多客户端代码......
  • 我想你只是读懂了我的想法!

标签: asp.net ajax json web-services asmx


【解决方案1】:

我是这样解决的:

    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;
}

【讨论】:

  • +1 这个问题,我希望自己能解决这个问题。我只是希望有一个简单的答案,不会以破坏现有客户的方式修改响应:(
  • 好吧,如果您的响应是由 Microsoft Web 服务发送的,那么您必须使用根“d”包装 JSON,因为它们的要求从 .NET 3.5 开始。因为您需要将额外的值(除了结果集)传回客户端,除非您想进行两次 Web 服务调用,否则您必须这样做。但是你必须处理异步调用,这意味着一个成功函数必须等待另一个成功函数成功完成。这只是更多的开销。
猜你喜欢
  • 1970-01-01
  • 2020-01-25
  • 2017-05-08
  • 2013-07-09
  • 1970-01-01
  • 1970-01-01
  • 2012-02-18
  • 2021-01-05
  • 2019-09-29
相关资源
最近更新 更多