Simple use of Json data parsing, json data parsing
Simply remember the simple and practical Json parsing:
Scenario: Json data uploaded from the background to the client, similar:
string jsonObject="{'Name':'Jack','Age':25}";string jsonArray = "[{'Name':'Jhon','Age':23},{'Name':'Jack','Age':25}]";
The client can define a class. The attributes in the class correspond to the corresponding fields in the data.
class Student{ public string Name { get; set; } public int Age { get; set; }}
Add a reference to Newtonsoft. Json using the Nuget package, and add the using Newtonsoft. Json. Linq; namespace.
Create a JToken object and parse the above string:
JToken jtoken = JToken.Parse(jsonObject); JToken jtoken2=JToken.Parse(jsonArray);
Then you can convert the data to the corresponding object:
if (jtoken1 is JObject) { Student s=jtoken.ToObject<Student>(); Console.WriteLine(s.Name); Console.WriteLine(s.Age); }if (jtoken2 is JArray){ List<Student> students = jtoken2.ToObject<List<Student>>(); foreach (var student in students) { Console.WriteLine(string.Format("Name:{0}\tAge:{1}", student.Name, student.Age)); }}
A Simple Method for parsing data :)
Time: 10 min