使用ServiceStack.Text(来自Nuget.org)将数据集序列化为json时遇到问题。我使用的是最新稳定版本 4.0.50 和 VS 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);
}
}
}
建议任何人?
答案 0 :(得分:2)
ServiceStack的文本序列化器都没有明确支持DataSet,这对于序列化来说是一种可怕的类型。
像OrmLite这样的微型ORM最终更清晰,更易于使用,映射到clean POCO's that are ideal for serialization,例如,上述查询的等效代码为:
var customers = Db.Select<Customer>(q => q.Take(1));
var json = customers.ToJson();
var dto = json.FromJson<Customer>();
或者,如果您不想创建Customer类型,可以使用OrmLite's dynamic API's映射到丢失类型的对象列表:
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,比数据集小得多且速度快,那么您的问题就会少得多,您也可以将POCO或松散类型的Dictionary序列化为CSV ServiceStack.Text:
var csv = customers.ToCsv();
var csv = dict.ToCsv();