Tag: Pac read object string DLL Add Reference upload nbsp constructor
Reading a JSON-formatted string into a class
In this example, a JSON-formatted string JSON is created to read its contents into the person class
Running this code requires adding a reference to the dynamic library Newtonsoft.json
Program code:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;//need to reference Newtonsoft.Json.dllusingNewtonsoft.json;namespacejsontest{classProgram {/// <summary> ///Personnel category/// </summary> Public classPerson { Public stringName//name Public intAge//Age Public BOOLSex_is_male;//Sex Public structPartner//Partner { Public stringPartner_name;//Partner name Public intPartner_age;//Partner Age Public BOOLPartner_sex_is_male;//Partner Sex } PublicPartner Partner; Public string[] achievement;//Achievements//constructor Function PublicPerson () {name=""; Age=0; Sex_is_male=true; Partner.partner_name=""; Partner.partner_age=0; Partner.partner_sex_is_male=true; Achievement=NULL; } } Static voidMain (string[] args) { stringJSON =string. Concat ("{", "\ "name\": \ "Tsybius\",", "\ "age\":", "\ "Sex_is_male\": true,", "\ "Partner\":", " {", "\ "partner_name\": \ "Galatea\",", "\ "partner_age\":", "\ "Partner_sex_is_male\": false", " },", "\ "achievement\": [\ "ach1\", \ "ach2\", \ "ach3\"]", "}" ); //assigning content to the person classPerson p = jsonconvert.deserializeobject<person>(JSON); Console.WriteLine ("Name:"+p.name); Console.WriteLine ("Age :"+p.age); Console.WriteLine ("Sex_is_male:"+P.sex_is_male); Console.WriteLine ("Partner_name:"+p.partner.partner_name); Console.WriteLine ("Partner_age:"+p.partner.partner_age); Console.WriteLine ("Partner_sex_is_male:"+P.partner.partner_sex_is_male); Console.Write ("Achievement:"); foreach(stringAchvinchp.achievement) {Console.Write (ACHV+" "); } Console.WriteLine (); Console.ReadLine (); } }}
Operation Result:
END
Go C # JSON-formatted strings are read into the class