【问题标题】:ArgumentException returning LINQ results serialized to JSONArgumentException 返回序列化为 JSON 的 LINQ 结果
【发布时间】:2012-09-06 19:49:52
【问题描述】:

我正在尝试从 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 对象来自this CodeProject project

【问题讨论】:

    标签: asp.net json asmx


    【解决方案1】:

    看起来惰性查询执行让你受益匪浅。 LINQ 直到最后一刻才执行您的查询。在这种情况下,它在序列化线上。问题出在您的查询中,而不是序列化程序中。

    问题看起来像当您通过返回一个 XElement 对象(似乎没有实现 IComparable)并试图比较它们时崩溃。

    我会先做你的选择然后订购结果。

    var query = (from center in centerXml.Descendants("Center")
                         where center.Element("ServiceArea").Value == aff
                         select new { 
                             City = center.Element("City") //may need a .ToString() here to get the city name out
                         }).Distinct().OrderBy(x => x.City);
    

    【讨论】:

    • 太棒了,成功了。我确实需要 ToString() 进行比较。非常感谢!
    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多