C#中怎么解析JSON数据?
发布网友
发布时间:2022-04-25 16:19
我来回答
共2个回答
热心网友
时间:2023-10-16 17:53
首先要知道json 的格式 把dataset中datatable表中数据转成json格式 public static string JsonConvert(DataSet ds)
{
StringBuilder sb = new StringBuilder();
sb.Append("[");
for (int i=0;i<ds.Tables[0].Rows.Count;i++)
{
sb.Append("{");
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
sb.Append("");
sb.Append(ds.Tables[0].Columns[j].ColumnName);
sb.Append(":\"");
sb.Append(ds.Tables[0].Rows[i][j].ToString().Trim());
sb.Append("\",");
}
sb.Remove(sb.Length-1,1);
sb.Append("},");
}
sb.Remove(sb.Length-1,1);
sb.Append("]");
return sb.ToString();
} /// <summary>
/// 将Ilist转成json格式
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static string JsonConvert(IList<TransBody> list)
{
try
{
System.Runtime.Serialization.Json.DataContractJsonSerializer seializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(list.GetType());
using (MemoryStream ms = new MemoryStream())
{
seializer.WriteObject(ms, list);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
catch
{
return null;
}
}把json格式转成ILIST 格式
public static object ConvertJson(string json ,Type t)
{
try
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(t);
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return serializer.ReadObject(ms);
}
}
catch
{
return null;
}
}
热心网友
时间:2023-10-16 17:54
.net 3.5 下有个system.web.script.serialization,有个类,JavaScriptSerializer 详情参考: http://hi.baidu.com/%B1%F9%D1%A9%D2%F8%C1%AB/blog/item/cfd4cf25cecddc228644f91c.html