Dynamic linq:Creating an extension method that produces JSON result

Tags: json linq c#
Question!

I'm stuck trying to create a dynamic linq extension method that returns a string in JSON format - I'm using System.Linq.Dynamic and Newtonsoft.Json and I can't get the Linq.Dynamic to parse the "cell=new object[]" part. Perhaps too complex? Any ideas? :

My Main method:

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 class

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]}
        //        ]
        // }

    }

}


Answers

This is really ugly and there may be some issues with the string replacement, but it produces the expected results:

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;
    }
}


Thanks for the quick response. However, note the required output does not have property names in the "cell" array ( that's why I was using object[]):

"cell":["FAMIA","Familia Arquibaldo",... vs. "cell":{"CustomerID":"FAMIA","CompanyName","Familia Arquibaldo",...

The result is meant to be used with a JQuery grid called "flexify" which requires the output in this format.



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);
    }
}


This video can help you solving your question :)
By: admin