Convert objects to JSON in C # using javascriptserializer

Source: Internet
Author: User

Want to convert a C # object into it's JSON equivalent? Here is a simple object from the system. Web. Script namespace that does exactly that:

System. Web. Script. serialization. javascriptserializer. It is stored in the system. Web. Extentions DLL (. NET Framework 3.5 only)

Using this object we serialize and deserialize objects in C #. Here is a quick sample:

A simple employee object:

Public classEmployee{Public StringName {Get;Set;}Public StringAge {Get;Set;}Public StringId {Get;Set;}}
 
 

Adding some instances of them to a list:

 
EmployeeOemployee1 =
NewEmployee{Name ="Pini", Id ="111", Age ="30"};
 
EmployeeOemployee2 =
 
NewEmployee{Name ="Yaniv", Id ="Cohen", Age ="31"};EmployeeOemployee3 =
NewEmployee{Name ="Yoni", Id ="Biton", Age ="20"};
 
List<Employee> Olist =NewList<Employee> ()
{Oemployee1, oemployee2, oemployee3 };
 
 

Serializing then:

System. Web. Script. serialization.JavascriptserializerOserializer =NewSystem. Web. Script. serialization.Javascriptserializer();StringSjson = oserializer. serialize (olist );

And here is the output:

 
[{"Name": "Pini", "Age": "30", "ID": "111 "},
 
{"Name": "Yaniv", "Age": "31", "ID": "Cohen "},
 
{"Name": "Yoni", "Age": "20", "ID": "Biton"}]
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.