厂址:http://www.cnblogs.com/yunfeifei/p/4086014.html
上代码:
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace JsonWithNewtonsoft { class Program { static void Main(string[] args) { //使用StringReader读取Json string jsonText = @"{""Name"":""Jack"",""Age"":""22""}"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); while (reader.Read()) { Console.WriteLine(reader.TokenType + "\t" + reader.ValueType + "\t" + reader.Value); } Console.WriteLine(); //使用JObject读取Json JObject jo = JObject.Parse(jsonText); string[] values = jo.Properties().Select(item => item.Name.ToString() + ":" + item.Value.ToString()).ToArray(); foreach (string s in values) { Console.WriteLine(s); } Console.WriteLine(); //解析数组型数据 string jsonArrayText1 = "[{‘Name‘:‘Tom‘,‘Age‘:‘16‘},{‘Name‘:‘Mary‘,‘Age‘:‘15‘}]"; JArray ja = (JArray)JsonConvert.DeserializeObject(jsonArrayText1); string name1 = ja[1]["Name"].ToString(); Console.WriteLine("数组型数据取法一:" + name1); Console.WriteLine(); JObject o = (JObject)ja[1]; string name2 = o["Name"].ToString(); Console.WriteLine("数组型数据取法二:" + name2); Console.WriteLine(); //嵌套格式 string jsonTexta = "{\"shanghai\":{\"zone\":\"浦东\",\"zone_en\":\"pudong\"}}"; JObject jsonObjt = JObject.Parse(jsonTexta); string zone = ((JObject)jsonObjt["shanghai"])["zone"].ToString(); string zoneEn = ((JObject)jsonObjt["shanghai"])["zone_en"].ToString(); Console.WriteLine(zone + "," + zoneEn); string jsonData = "{\"name\":\"lily\",\"age\":23,\"addr\":{\"city\":\"guangzhou\",\"province\":\"guangdong\"}}"; JObject jsonObj = JObject.Parse(jsonData); string namea = jsonObj["name"].ToString(); string age = jsonObj["age"].ToString(); string city = ((JObject)jsonObj["addr"])["city"].ToString(); string province = ((JObject)jsonObj["addr"])["province"].ToString(); Console.WriteLine(namea + "," + age + "," + city + "," + province); Console.WriteLine(GetJsonValue(jsonObj.Children(), "province")); Console.WriteLine(); string jsonDatab = "{\"addr\":[{\"city\":\"guangzhou\",\"province\":\"guangdong\"},{\"city\":\"guiyang\",\"province\":\"guizhou\"}]}"; JObject jsonObjm = JObject.Parse(jsonDatab); JArray jar = JArray.Parse(jsonObjm["addr"].ToString()); JObject j = JObject.Parse(jar[0].ToString()); Console.WriteLine(j["city"]); //序列化Json StringWriter sw = new StringWriter(); JsonWriter writer = new JsonTextWriter(sw); writer.WriteStartObject(); writer.WritePropertyName("Name"); writer.WriteValue("Jack"); writer.WritePropertyName("Age"); writer.WriteValue("26"); writer.WriteEndObject(); writer.Flush(); string jsonTextb = sw.GetStringBuilder().ToString(); Console.WriteLine(jsonTextb); Console.WriteLine(); //序列化Student类 Student stu = new Student() { Name="Jack",Age=20}; JsonSerializer serializer=new JsonSerializer(); StringWriter strw=new StringWriter(); serializer.Serialize(new JsonTextWriter(strw),stu ); Console.WriteLine(strw.GetStringBuilder().ToString()); //反序列化Student类 StringReader sr=new StringReader(strw.GetStringBuilder().ToString()); Student st = (Student) serializer.Deserialize(new JsonTextReader(sr), typeof (Student)); Console.WriteLine(st.Name + "=>" + st.Age); Console.WriteLine(); //序列化集合列表 List<Student> students=new List<Student>(); Student stu1=new Student(){Name="Jack",Age=20}; Student stu2=new Student(){Name="Tom",Age=21}; students.Add(stu1); students.Add(stu2); JsonSerializer serializer1=new JsonSerializer(); StringWriter strw1=new StringWriter(); serializer.Serialize(new JsonTextWriter(strw1),students); Console.WriteLine(strw1.GetStringBuilder().ToString()); Console.WriteLine(); List<Student2> student2s=new List<Student2>(); Student2 stu3=new Student2(){Name="Jack",Age=20,Phones = new List<string>{"18627900216","18571643691"}}; Student2 stu4 = new Student2() { Name = "Tom", Age = 21, Phones = new List<string> { "15972944805", "13349855388" } }; student2s.Add(stu3); student2s.Add(stu4); JsonSerializer serializer2=new JsonSerializer(); StringWriter strw2=new StringWriter(); serializer2.Serialize(new JsonTextWriter(strw2),student2s); Console.WriteLine(strw2.GetStringBuilder().ToString()); Console.Read(); } /// <summary> /// 遍历动态json对象 /// </summary> /// <param name="jToken">json对象的集合</param> /// <param name="key">json对象的属性</param> /// <returns>json对象的值</returns> public static string GetJsonValue(JEnumerable<JToken> jToken, string key) { IEnumerator enumerator = jToken.GetEnumerator(); while (enumerator.MoveNext()) { JToken jc = (JToken) enumerator.Current; if (jc is JObject || ((JProperty) jc).Value is JObject) { return GetJsonValue(jc.Children(), key); } else { if (((JProperty) jc).Name == key) { return ((JProperty) jc).Value.ToString(); } } } return null; } /// <summary> /// Student类,序列化时用 /// </summary> public class Student { /// <summary> /// 姓名 /// </summary> public string Name { get; set; } /// <summary> /// 年龄 /// </summary> public int Age { get; set; } } /// <summary> /// 修改Studnet类,添加电话号码字段 /// </summary> public class Student2 { /// <summary> /// 姓名 /// </summary> public string Name { get; set; } /// <summary> /// 年龄 /// </summary> public int Age { get; set; } //电话集合 public List<string> Phones { get; set; } } } }
上效果:
上附件:
时间: 2024-10-04 07:55:11