Dynamic动态解析Json操作用法讲解
DynJsonHelper操作用法大全:
1,将对象转换为json数据
2,将json数据转为对象
3,将数组List列表对象转换为json数据
4,将json数据转为List数组列表对象
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; namespace AutoHome.JsonDynamic { public partial class Test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { #region 将对象转换为json数据 //将对象转换为json数据 TestInfo info = new TestInfo() { Name = "Json解析", Num = 112, Time = DateTime.Now.ToString("g"), ByteStr = 0 }; string yunjsontr = DynJsonHelper.ToJson(info);//将对象转换为json数据 //输出的json串为:{"Name":"Json解析","Num":112,"Time":"2016-4-1 9:53","ByteStr":0} Response.Write("/******************将对象转换为json数据************************************/" + "<br>"); Response.Write(yunjsontr + "<br><br>"); #endregion #region 将json数据转为对象 //将json数据转为对象 //可以直接dyninfo.对象名 yunjsontr = "{\"Name\":\"Json解析\",\"Num\":112,\"Time\":\"2016-4-1 9:53\",\"ByteStr\":0}"; dynamic dyninfo = DynJsonHelper.ToObject(yunjsontr); Response.Write("/*****************将json数据转为对象****************************/" + "<br>"); Response.Write(dyninfo.Name + "-" + dyninfo.Num + "-" + dyninfo.Time + "-" + dyninfo.ByteStr + "<br><br>"); #endregion #region 将数组List列表对象转换为json数据 //将数组List列表对象转换为json数据 List<TestInfo> list = new List<TestInfo>() { new TestInfo { Name = "Json解析", Num = 112, Time = DateTime.Now.ToString("g"), ByteStr = 0 }, new TestInfo { Name = "Json格式化", Num = 113, Time = DateTime.Now.AddDays(-1).ToString("g"), ByteStr = 1 }, new TestInfo { Name = "Json序列化", Num = 114, Time = DateTime.Now.AddDays(1).ToString("g"), ByteStr = 2 }}; string jsonlist = DynJsonHelper.ToJson(list); Response.Write("/******************将数组List列表对象转换为json数据****************************/" + "<br>"); Response.Write(jsonlist + "<br><br>"); #endregion #region 将json数据转为List数组列表对象 //将json数据转为List数组列表对象 string newliststr = string.Empty; dynamic newlist = DynJsonHelper.ToObject(jsonlist); foreach (var item in newlist) { newliststr += item.Name + "-" + item.Num + "-" + item.Time + "-" + item.ByteStr + "<br>"; } Response.Write("/******************将json数据转为List数组列表对象****************************/" + "<br>"); Response.Write(newliststr); #endregion } } public class TestInfo { public string Name { get; set; } public int Num { get; set; } public string Time { get; set; } public byte ByteStr { get; set; } } } }