赞
踩
今天做项目遇到个问题,需要把json字符串转化list集合进行操作,
在网上搜了很多资料
比如
需要引用命名空间
using Newtonsoft.Json;
System.Web.Extensions.dll
public DataTable JsonTdb(string strJson)
{
DataTable dataTable = new DataTable(); //实例化
DataTable result;
try
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); //引用System.Web.Extensions javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值 ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(strJson); if (arrayList.Count > 0) { foreach (Dictionary<string, object> dictionary in arrayList) { if (dictionary.Keys.Count<string>() == 0) { result = dataTable; // return result; } if (dataTable.Columns.Count == 0) { foreach (string current in dictionary.Keys) { dataTable.Columns.Add(current, dictionary[current].GetType()); } } DataRow dataRow = dataTable.NewRow(); foreach (string current in dictionary.Keys) { dataRow[current] = dictionary[current]; } dataTable.Rows.Add(dataRow); //循环添加行到DataTable中 } } } catch { } return dataTable; // return result; }
public static DataTable jsonTable(string json)
{
return JsonConvert.DeserializeObject<DataTable>(json);
}
这二个主要针对于 简单josn格式 遇到嵌套的就会报异常
推荐用这个
需要引入命令空间
using Newtonsoft.Json.Linq;
JObject jobj = JObject.Parse(str);
这里填 你的data
JArray jar = JArray.Parse(jobj[“department”].ToString());
for (int i = 0; i < jar.Count; i++)
{
if (jar[i]["name"] == DeptName)
{
dingID = Convert.ToInt32(jar[i]["Id"]);
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。