C # JSON format

Source: Internet
Author: User

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

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.