动态 linq:创建生成 JSON 结果的扩展方法

Posted

技术标签:

【中文标题】动态 linq:创建生成 JSON 结果的扩展方法【英文标题】:Dynamic linq:Creating an extension method that produces JSON result 【发布时间】:2010-09-08 04:38:08 【问题描述】:

我一直在尝试创建一个动态 linq 扩展方法,该方法返回 JSON 格式的字符串 - 我正在使用 System.Linq.Dynamic 和 Newtonsoft.Json,但我无法让 Linq.Dynamic 解析“单元格=新对象 []" 部分。也许太复杂了?有任何想法吗? :

我的主要方法:

static void Main(string[] args)

    NorthwindDataContext db = new NorthwindDataContext();
    var query = db.Customers;
    string json = JSonify<Customer>
                    .GetJsonTable(
                        query, 
                        2, 
                        10, 
                        "CustomerID"
                        , 
                        new string[] 
                             
                                "CustomerID", 
                                "CompanyName", 
                                "City", 
                                "Country", 
                                "Orders.Count"
                            );
    Console.WriteLine(json);

JSonify 类

public static class JSonify<T>

    public static string GetJsonTable(
        this IQueryable<T> query, 
        int pageNumber, 
        int pageSize, 
        string IDColumnName, 
        string[] columnNames)
    
        string selectItems =
            String.Format(@"
                        new
                        
                            0 as ID,
                            cell = new object[]1
                        ", 
                          IDColumnName, 
                          String.Join(",", columnNames));

        var items = new
        
            page = pageNumber,
            total = query.Count(),
            rows =
                query
                    .Select(selectItems)
                    .Skip(pageNumber * pageSize)
                    .Take(pageSize)
        ;

        return javascriptConvert.SerializeObject(items);
        // Should produce this result:
        // 
        //    "page":2,
        //    "total":91,
        //    "rows":
        //        [
        //        "ID":"FAMIA","cell":["FAMIA","Familia Arquibaldo","Sao Paulo","Brazil",7],
        //        "ID":"FISSA","cell":["FISSA","FISSA Fabrica Inter. Salchichas S.A.","Madrid","Spain",0],
        //        "ID":"FOLIG","cell":["FOLIG","Folies gourmandes","Lille","France",5],
        //        "ID":"FOLKO","cell":["FOLKO","Folk och fä HB","Bräcke","Sweden",19],
        //        "ID":"FRANK","cell":["FRANK","Frankenversand","München","Germany",15],
        //        "ID":"FRANR","cell":["FRANR","France restauration","Nantes","France",3],
        //        "ID":"FRANS","cell":["FRANS","Franchi S.p.A.","Torino","Italy",6],
        //        "ID":"FURIB","cell":["FURIB","Furia Bacalhau e Frutos do Mar","Lisboa","Portugal",8],
        //        "ID":"GALED","cell":["GALED","Galería del gastrónomo","Barcelona","Spain",5],
        //        "ID":"GODOS","cell":["GODOS","Godos Cocina Típica","Sevilla","Spain",10]
        //        ]
        // 

    


【问题讨论】:

【参考方案1】:

这真的很难看,字符串替换可能存在一些问题,但它会产生预期的结果:

public static class JSonify

    public static string GetJsonTable<T>(
        this IQueryable<T> query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames)
    
        string select = string.Format("new (0 as ID, \"CELLSTART\" as CELLSTART, 1, \"CELLEND\" as CELLEND)", IDColumnName, string.Join(",", columnNames));
        var items = new
        
            page = pageNumber,
            total = query.Count(),
            rows = query.Select(select).Skip((pageNumber - 1) * pageSize).Take(pageSize)
        ;
        string json = JavaScriptConvert.SerializeObject(items);
        json = json.Replace("\"CELLSTART\":\"CELLSTART\",", "\"cell\":[");
        json = json.Replace(",\"CELLEND\":\"CELLEND\"", "]");
        foreach (string column in columnNames)
        
            json = json.Replace("\"" + column + "\":", "");
        
        return json;
    
  

【讨论】:

【参考方案2】:

感谢您的快速回复。 但是,请注意所需的输出在“单元格”数组中没有属性名称(这就是我使用 object[] 的原因):

"cell":["FAMIA","Familia Arquibaldo",... 对比 "cell":"CustomerID":"FAMIA","CompanyName","Familia Arquibaldo",...

结果旨在与名为“flexify”的 JQuery 网格一起使用,该网格需要这种格式的输出。

【讨论】:

【参考方案3】:
static void Main(string[] args)

    NorthwindDataContext db = new NorthwindDataContext();
    var query = db.Customers;
    string json = query.GetJsonTable<Customer>(2, 10, "CustomerID", new string[] "CustomerID", "CompanyName", "City", "Country", "Orders.Count" );
   

public static class JSonify

    public static string GetJsonTable<T>(
        this IQueryable<T> query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames)
    
        string select = string.Format("new (0 as ID, new (1) as cell)", IDColumnName, string.Join(",",     columnNames));
        var items = new
        
            page = pageNumber,
            total = query.Count(),
            rows = query.Select(select).Skip((pageNumber - 1) * pageSize).Take(pageSize)
        ;
        return JavaScriptConvert.SerializeObject(items);
    
  

【讨论】:

以上是关于动态 linq:创建生成 JSON 结果的扩展方法的主要内容,如果未能解决你的问题,请参考以下文章

动态生成 LINQ 查询

如何使用LINQ中的条件重新排列选择结果

创建 Where 查询的 LINQ 扩展方法

未使用 MVC 从 Json Result 获取 Ajax 成功方法中的 LINQ 连接查询结果,但结果显示正确

linq 动态判断

使用 C# 和 Linq 动态生成 kml 文件 [重复]