一、序列化一个DataSet
1.首先创建一个DataSet对象.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace JSONDemo
{
public class DataSetClass
{
public DataSet MyDataSet()
{
DataSet myDataSet = new DataSet();
myDataSet.Namespace = "GongHuiJson";
DataTable table1 = new DataTable();
DataColumn idColumn = new DataColumn("id", typeof(int));
idColumn.AutoIncrement = true;
idColumn.AutoIncrementSeed = 1;
idColumn.AutoIncrementStep = 2;
table1.Columns.Add(idColumn);
table1.Columns.Add(new DataColumn("name", typeof(string)));
for (int i = 0; i < 3; i++)
{
DataRow newRow = table1.NewRow();
newRow[1] = "indexName" + i;
table1.Rows.Add(newRow);
}
myDataSet.Tables.Add(table1);
DataTable table2 = new DataTable();
table2.Columns.Add(new DataColumn("animal", typeof(string)));
table2.Columns.Add(new DataColumn("voice", typeof(string)));
DataRow row1 = table2.NewRow();
row1["animal"] = "cat";
row1["voice"] = "miaow";
table2.Rows.Add(row1);
DataRow row2 = table2.NewRow();
row2["animal"] = "dog";
row2["voice"] = "wang";
table2.Rows.Add(row2);
myDataSet.Tables.Add(table2);
return myDataSet;
}
}
}
2.序列化DataSet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GongHuiNewtonsoft.Json;
using GongHuiNewtonsoft.Json.Converters;
namespace JSONDemo
{
class Program
{
static void Main(string[] args)
{
DataSetClass ds = new DataSetClass();
string json = JsonConvert.SerializeObject(ds.MyDataSet(), Formatting.Indented);
Console.WriteLine(json);
}
}
}
3.序列后的结果
\
二、JSON反序列化DataSet
1.反序列化DataSet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GongHuiNewtonsoft.Json;
using GongHuiNewtonsoft.Json.Converters;
namespace JSONDemo
{
class Program
{
static void Main(string[] args)
{
string jsonDataSet = @"
{
'Table1':
[
{
'id':1,
'name':'indexName0'
},
{
'id':3,
'name':'indexName1'
},
{
'id':5,
'name':'indexName2'
}
],
'Table2':
[
{
'animal':'cat',
'voice':'miaow'
},
{
'animal':'dog',
'voice':'wang'
}
]
}";
DataSet myDs = JsonConvert.DeserializeObject<DataSet>(jsonDataSet);
Console.WriteLine("=========Table1==========");
DataTable table1 = myDs.Tables["Table1"];
foreach (DataRow row in table1.Rows)
{
Console.WriteLine(row[0] + "/" + row[1]);
}
Console.WriteLine("==========Table2=========");
DataTable table2 = myDs.Tables["Table2"];
foreach (DataRow row in table2.Rows)
{
Console.WriteLine(row["animal"] + "-" + row["voice"]);
}
}
}
}
2.反序列后的结果
JSON源代码下载地址:http://download.youkuaiyun.com/detail/lovegonghui/9342751