JSON数据格式在当前前端开发中已经非常流行了,因为他简洁明了的语法(结构简洁,容易理解,适用性强)不仅受到开发者的青睐也有利于网络数据的传输,由于在数据传输的时候一般都会以JSON字符串的形式进行传递,所以无论前端还是后端都需要对他进行解析,解析为JSON对象后才能很方便的进行数据操作,因此在.NET的WEB开发中如何对JSON字符串进行解析是一个开发者应该了解的技术
using Newtonsoft.Json; public partial class api_HomeApi : System.Web.UI.Page { /// <summary> /// 首页数据 /// </summary> private void homeData() { Hashtable data = new Hashtable(); //使用table来构建返回多个键值对 ArrayList navList = getNavList(); ArrayList priceList = getPriceList(); data.Add("nav", navList); //将列表放入table中 data.Add("price", priceList); data.Add("img_right", "../iam/img1.jpg,../iam/img2.jpg"); //将字符串放入table中 data.Add("img_bottom", "../iam/img3.jpg,../iam/img4.jpg"); this.Response.AddHeader("Content-Type", "application/json; charset=utf-8"); //声明返回格式 this.contractrJSONHelper.responseSuccess(this.Response, "", JsonConvert.SerializeObject(data), true); //使用Newtonsoft.Json } }
请求结果如下:
{ "code": "200", "data": { "nav": [ { "data": [ { "id": 1, "changjia": "test1" } ], "title": "t1" }, { "data": ["1", "2"], "title": "t2" }, { "data": ["3", "4"], "title": "t3" } ], "price": [ { "id": 1, "data": [ { "nr": "1" } ], "title": "tt1" }, { "id": 2, "data": [], "title": "tt2" } ], "img_right": "../iam/img1.jpg,../iam/img2.jpg", "img_bottom": "../iam/img3.jpg,../iam/img4.jpg" }, "msg": "" }
class Cat { private string name = "scat"; public string Name { get { return name; } set { name = value; } } private int age = 10; } class Program { static void Main(string[] args) { Cat catObj = new Cat(); JavaScriptSerializer js = new JavaScriptSerializer(); string json = js.Serialize(catObj); Console.WriteLine(json); Cat cat = js.Deserialize<Cat>(json); Console.WriteLine(cat.Name); } }
System.Runtime.Serialization.dll
,命名空间 System.Runtime.Serialization.Json
,被序列化的类需要加 Windows Communication Foundation (WCF) 数据协定声明,否则会抛出异常 InvalidDataContractException
,(正在序列化的类型不符合数据协定规则。 例如,DataContractAttribute 特性未应用于该类型),代码如下:[DataContract(Name = "sCat")] class Cat { [DataMember(Name = "sname")] private string name = "scat"; [DataMember(Name = "sName")] public string Name { get { return name; } set { name = value; } } [DataMember(Name = "sage")] private int age = 10; } class Program { static void Main(string[] args) { Cat cat = new Cat(); DataContractJsonSerializer js = new DataContractJsonSerializer( typeof (Cat)); MemoryStream ms = new MemoryStream(); //使用内存流 js.WriteObject(ms, cat); ms.Position = 0; string json = Encoding.Default.GetString(ms.ToArray()); Console.WriteLine(json); MemoryStream ms_new = new MemoryStream(Encoding.Default.GetBytes(json)); Cat new_cat = js.ReadObject(ms_new) as Cat; Console.WriteLine(new_cat.Name); } }