将带有关联的数据集转换为JSON字符串 [英] Convert Dataset with Relation to JSON string

查看:131
本文介绍了将带有关联的数据集转换为JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种将数据集及其表之间的关系转换为JSON字符串的方法.

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

这是我的数据集序列化程序代码,如何使表嵌套(例如在asp.net的嵌套接收器中?)

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

谢谢

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

推荐答案

我的解决方案是: 将数据集转换为XmlDocument并调用函数tha将XmlDocument序列化为Json String. 我在以下站点的Json库中找到了此功能: http://json.codeplex.com/releases/view/74287

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

我的代码:

    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?

这篇关于将带有关联的数据集转换为JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆