我正在尝试从 ASMX Web 服务返回序列化为 JSON 的 LINQ 结果。据我所知,这应该可以工作,所以我必须遗漏一些东西。
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetCitiesForAffiliate(string aff)
{
XDocument centerXml = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/Centers.xml"));
var query = (from center in centerXml.Descendants("Center")
where center.Element("ServiceArea").Value == aff
orderby center.Element("City") ascending
select new {
City = center.Element("City")
}).Distinct();
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(query);
return json;
}
serializer.Serialize(query) 行抛出 ArgumentException:At least one object must implement IComparable.
我认为问题可能是我选择了一个匿名对象,但键入该对象并没有这样做。我确定我只是错过了一些愚蠢的东西吗?
有趣的是,这个以前的版本运行良好:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetCitiesForAffiliate(string aff)
{
TextFileReader reader1 = new TextFileReader(HttpContext.Current.Server.MapPath("~/App_Data/Centers.csv"), ",");
var query = (from cols in reader1
where cols[3].Equals(aff)
orderby cols[2] ascending
select new { City = cols[2] }).Distinct();
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(query);
return json;
}
TextFileReader 对象来自此 CodeProject 项目。