2

I'm looking for way to convert dataSet with relations between its tables to JSON string.

this is my code for dataset serializer, how can I make the tables to be nested (like in nested reapeter of asp.net?)

thanks,

Avital

    public static string DataTableToJSON(DataSet dt)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string str = serializer.Serialize(ToDictionary(dt));
        return str;
    }

    private static object RowsToDictionary(DataTable table)
    {
        var columns = table.Columns.Cast<DataColumn>().ToArray();
        return table.Rows.Cast<DataRow>().Select(r => columns.ToDictionary(c => c.ColumnName, c => r[c].ToString().Trim().Replace("'", "\'")));
    }

    private static object RowsToDictionary(DataSet table)
    {
        return table.Tables.Cast<DataTable>().ToDictionary(t => t.TableName, t => RowsToDictionary(t));    
    }


    private static Dictionary<string, object> ToDictionary(DataSet table)
    {
        Dictionary<string, object> dic = new Dictionary<string, object>();           
        if (table != null)
            dic.Add(table.DataSetName, RowsToDictionary(table));
        return dic;
    }
avital
  • 71
  • 1
  • 6

1 Answers1

5

My solution is: convert the dataset to XmlDocument and calling to function tha make serialization of XmlDocument to Json String. I found this function in Json library at the site: http://json.codeplex.com/releases/view/74287

My code:

    DataSet resultSet = new DataSet("Table");

.. fill dataset with datatables and relations....

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(resultSet.GetXml());
    string jsonText = JsonConvert.SerializeXmlNode(doc).Replace("null", "\"\"").Replace("'", "\'");
    return jsonText;

It work perfectly. anybody have more efficient solution?

avital
  • 71
  • 1
  • 6