开源项目提供的一个读取示例
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Newtonsoft.Json.Tests.Documentation.Samples.Json { public class ReadJsonWithJsonTextReader { public void Example() { #region Usage string json = @"{ 'CPU': 'Intel', 'PSU': '500W', 'Drives': [ 'DVD read/writer' /*(broken)*/, '500 gigabyte hard drive', '200 gigabype hard drive' ] }"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); while (reader.Read()) { if (reader.Value != null) Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value); else Console.WriteLine("Token: {0}", reader.TokenType); } // Token: StartObject // Token: PropertyName, Value: CPU // Token: String, Value: Intel // Token: PropertyName, Value: PSU // Token: String, Value: 500W // Token: PropertyName, Value: Drives // Token: StartArray // Token: String, Value: DVD read/writer // Token: Comment, Value: (broken) // Token: String, Value: 500 gigabyte hard drive // Token: String, Value: 200 gigabype hard drive // Token: EndArray // Token: EndObject #endregion } } }
json 读取
//json读取示例 public void jsonreadsample() { string jsonstr = "{"Name" : "Jack", "Age" : 34, "Colleagues" : [{"Name" : "Tom" , "Age":44},{"Name" : "Abel","Age":29}] }"; //将json转换为JObject JObject jo = JObject.Parse(jsonstr); JToken ageToken=jo["Name"]; //获取该员工的姓名 Console.WriteLine(ageToken.ToString()); //获取该员工同事所有姓名(读取json数组) var names=from staff in jo["Colleagues"].Children() select (string)staff["Name"]; foreach (var name in names) Console.WriteLine(name); }
url编码
//URL encode public String UrlEncoded(string str) { StringBuilder sb = new StringBuilder(); byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str) for (int i = 0; i < byStr.Length; i++) { sb.Append(@"%" + Convert.ToString(byStr[i], 16).ToUpper()); } return (sb.ToString()); }