如何使WebMethods序列化ExpandoObject

时间:2012-02-21 23:05:06

标签: asp.net json asmx expandoobject

我有一个类似于此的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

我从webservice上回来的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序列化的方式?

1 个答案:

答案 0 :(得分:4)

听起来你已经想到了这一点,但是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;
  }
}

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

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