gpt4 book ai didi

asp.net - 如何使 WebMethods 序列化 ExpandoObject

转载 作者:行者123 更新时间:2023-12-02 07:34:35 26 4
gpt4 key购买 nike

我有一个如下所示的 WebMethod,用于填充 jqGrid

[System.Web.Script.Services.ScriptService]
public class MyWebService: System.Web.Services.WebService
{
[WebMethod]
[Authorize(Roles = "Admin")]
public object GetPeople(bool _search, double nd, int rows, int page, string sidx, string sord)
{
var tbl = new DynamicModel("ConnStr", tableName: "Person", primaryKeyField: "ID");
var results = tbl.Paged(orderBy: sidx + " " + sord, currentPage: page, pageSize: rows);
return results;
}

}

“结果”是一个 System.Dynamic.ExpandoObject,具有 Items、TotalPages、TotalRecords 属性

我从网络服务返回的 json 看起来像这样

{
"d": [{
"Key": "TotalRecords",
"Value": 1
}, {
"Key": "TotalPages",
"Value": 1
}, {
"Key": "Items",
"Value": [
[{
"Key": "Row",
"Value": 1
}, {
"Key": "ID",
"Value": 1
}, {
"Key": "Name",
"Value": "Test Template"
}]
]
}]
}
} // Don't know why firebug put this extra bracket

理想情况下,我希望它返回时没有所有键和值业务,因为它不必要地使 json 膨胀,并且与 jqGrid 不能很好地配合。

有没有办法改变 ASP.NET 处理 ExpandoObject 序列化的方式?

最佳答案

听起来你已经明白了这一点,但这里是 something I threw together a while back为此:

public class ExpandoObjectConverter : JavaScriptConverter {
public override IEnumerable<Type> SupportedTypes {
get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(ExpandoObject) })); }
}

public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) {
ExpandoObject expando = (ExpandoObject)obj;

if (expando != null) {
// Create the representation.
Dictionary<string, object> result = new Dictionary<string, object>();

foreach (KeyValuePair<string, object> item in expando) {
if (item.Value.GetType() == typeof(DateTime))
result.Add(item.Key, ((DateTime)item.Value).ToShortDateString());
else
result.Add(item.Key, item.Value.ToString());
}

return result;
}
return new Dictionary<string, object>();
}

public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
return null;
}
}

然后,您只需将其添加到 <converters> 中即可web.config 中的部分,如您链接到的 MSDN 文章所示:

<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization>
<converters>
<add name="ExpandoObjectConverter" type="ExpandoObjectConverter"/>
</converters>
</jsonSerialization>
</webServices>
</scripting>
</system.web.extensions>
</configuration>

关于asp.net - 如何使 WebMethods 序列化 ExpandoObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9386739/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com