簡體   English   中英

ServiceStack.Text:將DataSet序列化為json

[英]ServiceStack.Text: serializing DataSet to json

我在使用ServiceStack.Text(來自Nuget.org)將數據集序列化為json時遇到麻煩。 我正在使用最新的穩定版本4.0.50VS 2015 我不斷

進程由於StackOverflowException而終止

我的代碼:

using System;
using System.Data;
using System.Data.SqlClient;
using ServiceStack.Text;

namespace TestServiceStackText
{
    class Program
    {
        static void Main(string[] args)
        {
            string ConnectionString = @"Server=MyServer; Database=NORTHWND; User Id=SomeUser; Password=SomePassword;";
            string SqlQuery = @"SELECT TOP 1 * FROM [NORTHWND].[dbo].[Customers]";

            // Create new dataset instance
            DataSet dataset = new DataSet();

            // Fill it with a little data: 1 table, 1 row
            using (var conn = new SqlConnection())
            {
                using (var da = new SqlDataAdapter())
                {
                    using (da.SelectCommand = conn.CreateCommand())
                    {
                        da.SelectCommand.CommandText = SqlQuery;
                        da.SelectCommand.Connection.ConnectionString = ConnectionString;
                        da.Fill(dataset);
                    }
                }
            }

            // Serialize to json: exception occurs here
            string json = TypeSerializer.SerializeToString<DataSet>(dataset);
            Console.WriteLine("Dataset serialized to json:\n {0}", json); 

            // Deserialize to DataSet
            DataSet ds = TypeSerializer.DeserializeFromString<DataSet>(json);
            Console.WriteLine("Name: {0}, Nr. of Tables: {1}", ds.DataSetName, ds.Tables.Count);
        }
    }
}

建議有人嗎?

ServiceStack的文本序列化程序都沒有對DataSet的顯式支持,而DataSet是可怕的序列化類型。

OrmLite之類的Micro ORM最終變得更加整潔和易於使用,這些映射可以清理非常適合序列化的POCO ,例如,上述查詢的等效代碼是:

var customers = Db.Select<Customer>(q => q.Take(1));

var json = customers.ToJson();
var dto = json.FromJson<Customer>();

或者,如果您不想創建客戶類型,則可以使用OrmLite的動態API映射到丟失類型的對象列表:

var list = Db.Select<List<object>>(
   "SELECT TOP 1 * FROM [NORTHWND].[dbo].[Customers]");

或字典:

var dict = Db.Select<Dictionary<string,object>>(
   "SELECT TOP 1 * FROM [NORTHWND].[dbo].[Customers]");

檢出northwind.servicestack.net項目,以獲取使用OrmLite和AutoQuery查詢Northwind數據集的代碼示例。

總而言之,如果您使用干凈的POCO代替每個序列化程序支持的數據集,並且數據集的大小和速度比DataSet的小得多和快得多,那么您將遇到的問題會少很多,還可以使用ServiceStack.Text將POCO或松散類型的Dictionary序列化為CSV。 :

var csv = customers.ToCsv();
var csv = dict.ToCsv();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM