5

我有一个看起来像这样的 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;
    }

}

"results" 是一个 System.Dynamic.ExpandoObject,具有 Items、TotalPages、TotalRecords 属性

我从 web 服务返回的 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

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

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

4

1 回答 1

4

听起来你已经想通了,但这是我不久前为了做到这一点而拼凑起来的:

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>
于 2012-02-22T00:58:44.700 回答