標籤:des 解析 string javascrip span system beijing extension 效果
1、建立json數組,例:
JArray arrFile = new JArray();arrFile.Add(new JObject() { new JProperty("FilePath",jArray[i]["FilePath"].ToString()),//檔案路徑 new JProperty("FileName",jArray[i]["FileName"].ToString()),//檔案名稱 new JProperty("Type",jArray[i]["Type"].ToString()),//檔案類型 new JProperty("IsDirectory",jArray[i]["IsDirectory"].ToString()),//是否檔案夾 new JProperty("ParentNode",jArray[i]["ParentNode"].ToString()),//檔案夾路徑 new JProperty("Date",jArray[i]["Date"].ToString()),//日期 });
2、Json序列化,例:
簡單對象Person:
public class Person { public string Name { get; set; } public int Age { get; set; } }
序列化為JSON字串:
protected void Page_Load(object sender, EventArgs e) { Person p = new Person(); p.Name = "張三"; p.Age = 28; string jsonString = JsonHelper.JsonSerializer<Person>(p); Response.Write(jsonString); }
輸出結果:
{"Age":28,"Name":"張三"}
3、還原序列化Demo:
protected void Page_Load(object sender, EventArgs e) { string jsonString = "{\"Age\":28,\"Name\":\"張三\"}"; Person p = JsonHelper.JsonDeserialize<Person>(jsonString); }
ASP.NET中的JSON序列化和還原序列化還可以使用JavaScriptSerializer,在System.Web.Script.Serializatioin命名空間下,需引用System.Web.Extensions.dll.也可以使用JSON.NET.
4、讀取json數組中特定的參數值
//讀取json數組中特定的參數值string readStream = sr.ReadToEnd();JArray jArray = (JArray)JsonConvert.DeserializeObject(readStream);if (jArray.Count>0){ for (int i = 0; i < jArray.Count; i++) { string str = jArray[i]["FilePath"].ToString(); } }
5、Json字串解析
Json字串普通格式解析(常用):
string jsonText = "{\"zone\":\"海澱\",\"zone_en\":\"haidian\"}";JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);string zone = jo["zone"].ToString();string zone_en = jo["zone_en"].ToString();
Json字串嵌套格式解析:
string jsonText = "{\"beijing\":{\"zone\":\"海澱\",\"zone_en\":\"haidian\"}}";JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);string zone = jo["beijing"]["zone"].ToString();string zone_en = jo["beijing"]["zone_en"].ToString();
Json字串數組格式解析
string jsonArrayText = "[{‘a‘:‘a1‘,‘b‘:‘b1‘},{‘a‘:‘a2‘,‘b‘:‘b2‘}]"; //"[{‘a‘:‘a1‘,‘b‘:‘b1‘}]即使只有一個元素,也需要加上[]string jsonArrayText = "[{\"a\":\"a1\",\"b\":\"b1\"},{\"a\":\"a2\",\"b\":\"b2\"}]"; //上面寫法和此寫法效果一樣JArray jArray = (JArray)JsonConvert.DeserializeObject(jsonArrayText);//jsonArrayText必須是帶[]數組格式字串string str = jArray[0]["a"].ToString();
C# Json數組序列化和反序列總結