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":"张三"}
二、例:
非数组格式用JObject加载:
string jsonText = "{"a":"aaa","b":"bbb","c":"ccc"}"; //"{'a':'aaa','b':'bbb','c':'ccc'}"; var mJObj = JObject.Parse(jsonText);
数组格式用JArray加载:
string jsonText1 = "[{'a':'aaa','b':'bbb','c':'ccc'},{'a':'aa','b':'bb','c':'cc'}]"; //"[{"a":"aaa","b":"bbb","c":"ccc"},{"a":"aa","b":"bb","c":"cc"}]"; var mJObj1 = JArray.Parse(jsonText1);
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();