Implement JSON functionality in C #!
JSON has recently been used to pass information to the server, so I have a little bit of a look at JSON.
If you want to use the JSON feature in C #, first we need to use the Newtonsoft.json namespace, and we can install the files we need with NuGet.
You can add files by entering Install-package Newtonsoft.json in the NuGet console.
Then reference the Newtonsoft.json namespace.
Then it's how to convert the object we built into a JSON string.
I created a student class
class Student { publicstringgetset;} Public string Get Set ; } Public string Get Set ; } }
The student object is then serialized to generate a JSON string
list<student> students =NewList<student>(); Students. ADD (NewStudent {Name ="Zhu", Classnum ="1", id ="1" }); Students. ADD (NewStudent {Name ="Yu", Classnum ="1", id ="1" }); Students. ADD (NewStudent {Name ="Quan", Classnum ="1", id ="1" }); Students. ADD (NewStudent {Name ="ZZ", Classnum ="1", id ="1" }); Students. ADD (NewStudent {Name ="ZDD", Classnum ="1", id ="1" }); stringJsonstring =Jsonconvert.serializeobject (students); Console.WriteLine (jsonstring); Console.WriteLine ();
Anonymous classes are also available when we want to generate JSON strings, and we do not need to establish objects separately.
Of course, you can deserialize a JSON string into a student object
stringInputjsonstring =@"[{name: ' Zhu ', classnum: ' 1 ', ID: ' 1 '}, {name: ' Yu ', Classnum: ' 2 ', ID: ' 2 '}, {Nam E: ' Quan ', Classnum: ' 1 ', ID: ' 2 '}]"; Jarray Jsonobj=Jarray.parse (inputjsonstring); List<student> objects =NewList<student>(); Objects= jsonconvert.deserializeobject<list<student>>(inputjsonstring); foreach(Student iteminchobjects) {Console.WriteLine ("name:{0},classnum:{1},id:{2}", item. Name, Item.classnum, item.id); }
We need to add list<student> to deserializeobject<t> to let the function return the List<student> object.
C # JSON format