写:
StringWriter sw = new StringWriter(); JsonWriter writer = new JsonWriter(sw); //如果报错则使用JsonWriter writer = new JsonTextWriter(sw); writer.WriteStartArray(); writer.WriteValue("JSON!"); writer.WriteValue(1); writer.WriteValue(true); writer.WriteStartObject(); writer.WritePropertyName("property"); writer.WriteValue("value"); writer.WriteEndObject(); writer.WriteStartObject(); writer.WritePropertyName("data"); writer.WriteValue(_str); writer.WriteEndObject(); writer.WriteEndArray(); writer.Flush(); string jsonText = sw.GetStringBuilder().ToString(); Response.Write(jsonText);
读: 注意格式;
string message ={"ObjectId":"fd4169f8-337d-4796-be8c-c35f1075f151","SequenceNo":"0000000791"} var obj = Newtonsoft.Json.Linq.JObject.Parse(message); if (obj == null) { throw new Exception("获取消息失败!"); } var Id = obj["ObjectId"].ToString(); var DeptNo = obj["SequenceNo"].ToString();
使用JObject读写字符串:
JObject jo = JObject.Parse(jsonText);
string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray();
数组格式解析成二维数组;
StringBuilder sb = new StringBuilder(); protected void Page_Load(object sender, EventArgs e) { string jsontext = "[{ID:'1',Name:'zhangsan',Other:[{Age:'111'}]}]"; //jsontext数组格式 Newtonsoft.Json.Linq.JArray ja = (Newtonsoft.Json.Linq.JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(jsontext); foreach (Newtonsoft.Json.Linq.JObject item in ja) { string aa = item["Name"].ToString(); Newtonsoft.Json.Linq.JArray ja0 = (Newtonsoft.Json.Linq.JArray)item["Other"];//数组格式 foreach (Newtonsoft.Json.Linq.JObject item0 in ja0) { string bb = item0["Age"].ToString(); } }
数组型数据 string jsonArrayText1 = "[{'a':'a1','b':'b1'},{'a':'a2','b':'b2'}]"; JArray ja = (JArray)JsonConvert.DeserializeObject(jsonArrayText1); string ja1a = ja[1]["a"].ToString(); //或者 JObject o = (JObject)ja[1]; string oa = o["a"].ToString(); 嵌套格式 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到给定的匿名对象.
/// <summary> /// 反序列化JSON到给定的匿名对象. /// </summary> /// <typeparam name="T">匿名对象类型</typeparam> /// <param name="json">json字符串</param> /// <param name="anonymousTypeObject">匿名对象</param> /// <returns>匿名对象</returns> public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject) { T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject); return t; }
http://www.cnblogs.com/huangcong/p/7048501.html
http://www.cnblogs.com/songjiali/p/6165281.html