//把一个json字符串转换为DataTable
string user_json="{\"userName\":\"张三\"}";
string userName="";
DataTable dt = JsonConvert.DeserializeObject<DataTable>("[" + user_json+ "]");
for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt1.Rows[i]; userName= dr[0].ToString(); }
//把DataTable转换为Json字符串
public string ToJson(DataTable dt)
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
ArrayList arrayList = new ArrayList();
foreach (DataRow dataRow in dt.Rows)
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
foreach (DataColumn dataColumn in dt.Columns)
{
dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName]);
}
arrayList.Add(dictionary);
}
return javaScriptSerializer.Serialize(arrayList);
}
//把一个json字符串转换为一个对象
public void getClass()
{ string json = "{\"str1\":\"ok\",\"class2\":{\"str2\":\"水果\",\"class3\":[{\"str3\":\"苹果\"},{\"str3\":\"香蕉\"}]}}"; JavaScriptSerializer js = new JavaScriptSerializer(); //实例化一个能够序列化数据的类(需要Newtonsoft.Json.dll) Class1 list = js.Deserialize<Class1>(json); //将json数据转换为对象类型并赋值给list string str1 = list.str1; string str2 = list.class2.str2; string str30 = list.class2.class3[0].str3; string str31 = list.class2.class3[1].str3; } public class Class1 { public string str1 { get; set; } public Class2 class2; }public class Class2 {
public string str2{ get; set; } public List<Class3> class3; }public class Class3 {
public string str3{ get; set; } }//根据对象转换为Json字符串
public string getJsonStr(Class1 class1) {
StringBuilder sb = new StringBuilder();JavaScriptSerializer jsonStr = new JavaScriptSerializer(); //将list对象转换为json数据(需要Newtonsoft.Json.dll)
jsonStr.Serialize(class1, sb);
return sb.ToString();
}--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
浅谈,如果代码有问题,欢迎指出。