下面是用到的方法
Reading the specified file that contains a json string (object sender, EventArgs e) { //Judge whether the specified file exists. if (File.Exists(filename)) { //Getting the string that is a specified file using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8)) { string json = sr.ReadToEnd(); //analyze the json string. txtOrgJson.Text = json; List<Person> people = jss.Deserialize<List<Person>>(json); StringBuilder sb = new StringBuilder(); PropertyInfo[] piArr = typeof(Person).GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (people.Count == 0) { DeserializeToObject(json); return; } //Get the name and value of the specified class Person automatically. foreach (var person in people) { sb.Clear(); foreach (PropertyInfo pi in piArr) { sb.Append(pi.Name + "=" + pi.GetValue(person)); sb.Append("\t "); } listAll.Items.Add(sb.ToString()); //listAll.Items.Add("name=" + person.Name + "\tid=" + person.Id + "\tphone=" + person.Phone); } } } else { MessageBox.Show("Cannot find the specified file.Please click the up button of this."); } } 6.总结以及如何移植到web和其他序列化途径 先写这么多,你有什么疑问也可以留言交流一下,该案例仅供参考,不代表标准案例。另外,由于这里用的是WinForm开发,你在Web里通过POST方法传入json数据时,可能需要通过下面的方法获取到json string StreamReader reader = new StreamReader(context.Request.InputStream); //比如得到json字符串:strJson={"key3":"xdp-gacl","key4":"白皇"} String strJson = HttpUtility.UrlDecode(reader.ReadToEnd());然后下面就是按上面的案例中的方法进行优化,调整。
另外呢,如果是传入的JSON string是一个,那么可以通过键值对的方式来读取:
调用方式
Dictionary<String, Object> dicParameter = GetParameter(context); string key3 = dicParameter["keyword"].ToString();另外呢,除了上面的序列化之外,还可以用下面的方法:
(object item) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, item); StringBuilder sb = new StringBuilder(""); sb.Append(Encoding.UTF8.GetString(ms.ToArray())); return sb.ToString(); } }需要你引用:using System.Runtime.Serialization.Json;
好,暂时就分享到这里。谢谢!