json字符串转换为dataset(datatable)

///jsong字符串:[{ “success”: true,“message”: “请求成功”,“data”: [{“字段1”: “值1” }, {“字段2”: “值2” }, {“字段3”: “值3” }, {“字段4”: “值4” }]}]
///返回结果:返回的dataset中有两个datatable,resTable是返回值内容,dataTable是data内容

public static Dat aSet ToDat aSet (string json)
{
	Dat aSet dat aSet=new Dat aSet () ://突例化
	DataTable resTable = new DataTable(" resTable"): //突 例化并指定名称;DataTable dataTable = new DataTable(" dataTable"): 1/突 例化并指定名称DataSet result = dat aSet :try

	J.avaScriptSerializer javaScriptSerializer = new JavaScriptSerializer() :javaScript Serializer. MaxJsonLength = Int32. MaxValue: //取得最大数値
	ArrayList arrayList = javaScriptSerializer. Deserialize<ArrayList> (json) :if (arr ayList. Count > O){

	foreach (DictionaryKstring, object> dictionary in arrayList)
	{
		if (dict ionarx, Keys. Countsstrins20.= , O)
		{
			result = dataSet :
			return result :
		}
		//--Columns
		if (dataTable. Columns. Count == O)

		foreach (string current in dictionary. Keys)
		{
			if (current != "data")
				resTable.Columns.Add (current, dictionary [current]. GetType 0)) :
			else
			{
				ArrayListlist = dictionary[current] as ArrayList :
				foreach (Dictionary<string, object〉 dic in list)
				{
					foreach (string key in dic. Keys)
					{
						dataTable.Columns.Add (key, dic [key]. GetType()) :
					}
					brealk :
				}
			}
		}
	}
	//--Rows 
	string root = "" :
	DạtaRow resRow = resTable.NewRow() :
	foreach (string current in dictionary. Keys)
	{
		if (current!=" data" )
		{
			resRow [current] = dictionary [current]. ToStringO :
		}
	}
	resTable. Rows. Add (resRow) :	


	foreach (string current in dictionary. Keys)
	{
		ịf (current = "data")
		{
			ArrayList list = dictionary[current] as ArrayList :
			foreach (Dict ionary<string, object> dic in list)
			{
				DạtaRow dataRow = dataTable.NewRow() :
				foreach (string key in dic.Keys)
				{
					dat aRow[key] = dic[key] :
				}
				dataTable.Rows.Add (dataRow) :
			}
		}
	}

	çatch (Exceptionẹ) 
	{}
	result.Tables.Add(resTable) :
	result.Tables.Add(dat aTable) :
	return result:
}
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页