Simple use of Json data parsing, json data parsing

Source: Internet
Author: User

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

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.