A read example provided by an open source project
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Text;namespacenewtonsoft.json.tests.documentation.samples.json{ Public classReadjsonwithjsontextreader { Public voidExample () {#regionUsagestringJSON =@"{' CPU ': ' Intel ', ' PSU ': ' 500W ', ' Drives ': [' DVD read/writer '/* * (broken) * /, ' gigabyte hard drive ', ' $ gigabype hard drive '}"; JsonTextReader Reader=NewJsonTextReader (NewStringReader (JSON)); while(reader. Read ()) {if(Reader. Value! =NULL) Console.WriteLine ("Token: {0}, Value: {1}", reader. Tokentype, reader. Value); ElseConsole.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 read
//JSON read Sample Public voidjsonreadsample () {stringJsonstr ="{\ "name\": \ "Jack\", \ "age\": "Colleagues\": [{\ "name\": \ "tom\", \ "age\": 44},{\ "name\": \ "abel\", \ "age\": 2 9}]}"; //convert JSON to JobjectJobject Jo =Jobject.parse (JSONSTR); Jtoken Agetoken=jo["Name"];//get the name of the employeeConsole.WriteLine (agetoken.tostring ()); //get all the name of the employee colleague (read JSON array) varnames= fromStaffinchjo["colleagues"]. Children ()Select(string) staff["Name"]; foreach(varNameinchnames) Console.WriteLine (name); }
URL encoding
//URL encode PublicString urlencoded (stringstr) {StringBuilder SB=NewStringBuilder (); byte[] bystr = System.Text.Encoding.UTF8.GetBytes (str);//default is System.Text.Encoding.Default.GetBytes (str) for(inti =0; i < bystr.length; i++) {sb. Append (@"%"+ convert.tostring (Bystr[i], -). ToUpper ()); } return(sb.) ToString ()); }
C # manipulating JSON data using Newtonsoft.json