序列化数据集vb.net错误

时间:2012-08-24 15:45:47

标签: .net vb.net

当我尝试序列化自定义数据集时出现此错误。 我做错了什么,乖乖它应该很简单?

由于

错误     序列化“System.Globalization.CultureInfo”类型的对象时检测到循环引用。

 Dim serializer As New JavaScriptSerializer()
            Dim arrayJson As String = serializer.Serialize(makeMYDataSET())

    Private Function makeMYDataSET() As DataSet


        ' Two DataTables.
        Dim table1 As DataTable = New DataTable("patients")
        table1.Columns.Add("name")
        'table1.Columns.Add("id")
        table1.Rows.Add("sam")
        table1.Rows.Add("mark")
        table1.Rows.Add("hjhkhkh")

        Dim table2 As DataTable = New DataTable("medications")
        'table2.Columns.Add("id")
        table2.Columns.Add("medication")
        table2.Rows.Add("atenolol")
        table2.Rows.Add("amoxicillin")

        ' Create a DataSet. Put both tables in it.
        Dim set1 As DataSet = New DataSet("office")
        set1.Tables.Add(table1)
        set1.Tables.Add(table2)


        Return set1

    End Function

2 个答案:

答案 0 :(得分:1)

无法在普通JavaScriptSerializer上使用DataSet


一种方法是将您的DataSet转换为XML,或者更好,首先将其转换为Dictionary

您可以使用此方法(来自CodeProject的示例):

Function DataSetToJSON(ds As DataSet) As String
    Dim dict = New Dictionary(Of String, Object)

    For Each dt As DataTable In ds.Tables
        Dim arr(dt.Rows.Count) As Object

        For i = 0 To dt.Rows.Count - 1
            arr(i) = dt.Rows(i).ItemArray
        Next

        dict.Add(dt.TableName, arr)
    Next

    Dim json = New JavaScriptSerializer
    Return json.Serialize(dict)
End Function

示例

 DataSetToJSON(makeMYDataSET())

<强>结果

  

{ “患者”:[[ “SAM”],[ “标记”],[ “hjhkhkh”],空], “药物”:[[ “阿替洛尔”],[ “阿莫西林”],空]}

答案 1 :(得分:-1)

DataSet somedataset;
XmlSerializer s = new XmlSerializer(typeof(Dataset));
StringWriter sw = new StringWriter();
s.Serialize(sw, somedataset);
string serialized = sw.ToString();

我认识它,但它确实有效 关于javascriptserialzer类,我之前没有使用它,但我认为它与xmlserializer有关。