This project has moved. For the latest updates, please go here.

How can I serialize a DataSet or DataTable to Json?

Dec 1, 2009 at 3:18 AM

Always we query data from database, and get data with DataSet or DataTable. Can I directly serialize a DataSet or DataTable into json?

            SqlCommand cmdJson = new SqlCommand();
            cmdJson.CommandText = "select * from DbTable";
            DataSet ds = accessor.ExecuteQuery(cmdJson);
            StringWriter sw = new StringWriter();
            Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer();
            ser.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
            using (Newtonsoft.Json.JsonWriter jw = new Newtonsoft.Json.JsonTextWriter(sw))
                jw.Formatting = Newtonsoft.Json.Formatting.Indented;
                ser.Serialize(jw, ds.Tables[0].Rows);
            string exit = sw.ToString();

why failed?

Dec 1, 2009 at 11:23 PM

I added DataSet/DataTable serialization in the latest version of the source code some time ago. It is on CodePlex if you want to get the source and build it yourself.

Dec 22, 2009 at 2:23 PM


I downloaded the lastest code, and built it, the serialization works fine, but, the de-serialization it couldn´t be done into a generic object ? like JObject or Object ?