This project has moved and is read-only. For the latest updates, please go here.

How can I serialize a DataSet or DataTable to Json?

Dec 1, 2009 at 4: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 2, 2009 at 12:23 AM

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 3: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 ?