Json.NET is a. NET Framework implementation of JSON, with which we can easily use JSON in. NET programs, such as parsing the key values of a JSON string, generating a JSON string, converting between objects, and so on. and is open source, very convenient for us to learn and use.
Json.NET's website: Https://www.newtonsoft.com/json
Here are some basic ways to usebefore using the following code, you need to add a reference
using Newtonsoft.json; using Newtonsoft.Json.Linq;
1. Reading the key value information in the Json string
Static voidMain (string[] args) { stringJstr ="{name: ' Momo ', Birthday: ' 2016-8-1 ', weidht:11.5, lovefoods: [' milk ', ' chicken ']}";//Json StringJobject jobj =NULL; Try{jobj= Jobject.parse (JSTR);//converts a JSON string to a jobject type, which is an exception if the JSON string is not valid. } Catch(Exception ex) {Console.WriteLine (ex). Message); return; } //read value by nameConsole.WriteLine ("========================= reading values by name"); Console.WriteLine (jobj["name"]); Console.WriteLine (Jobj.getvalue ("Birthday")); //Traverse all key-value pairsConsole.WriteLine ("========================= traversal of all key-value pairs"); foreach(varIteminchjobj) {Console.WriteLine (item. Key.tostring ()+": "+item. Value.tostring ()); } console.readline (); }
Output results
2. Generating a Json string
//generating a Json stringConsole.WriteLine ("========================= Generating a Json string"); Jobject JObj2=NewJobject (); stringName ="Tongtong"; intAge =2; Jarray Interests=NewJarray ("singing","Swim","watching TV"); Jobj2.add ("name", name); Jobj2.add (" Age", age); Jobj2.add ("Interests", interests); Console.WriteLine (Jobj2.tostring (formatting.indented));
Output results
3. Object and Json strings are converted to each other
First define a class
Public classPerson { Public stringName {Get;Set; } ="Momo"; PublicDateTime Birthday {Get;Set; } =NewDateTime ( .,8,1); Public DoubleWeight {Get;Set; } =11.5; Public string[] Lovefoods {Get;Set; } =New string[] {"Milk","Chicken" }; }
Using the methods in JsonConvert to convert
//object into JsonConsole.WriteLine ("========================= objects into Json"); Person Person1=NewPerson (); Person1. Name="Lily"; stringJSTR1 =Jsonconvert.serializeobject (Person1, formatting.indented); Console.WriteLine (JSTR1); //Json into ObjectsConsole.WriteLine ("=========================json into Objects"); Person Person2= jsonconvert.deserializeobject<person>(JSTR1); Console.WriteLine (Person2. Name);
Output results
Summarize
Json.NET more than that, check out the Help documentation for further learning.
Help document Address: https://www.newtonsoft.com/json/help/html/Introduction.htm
Note: Here the program tests are using Json.NET 2.0 DLLs.
Json.NET Getting Started