假设我们正在序列化“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/