Simple Example of JavaScriptSerializer implementing JSON serialization and deserialization

Source: Internet
Author: User

1. JSON serialization

Using System; using System. collections. generic; using System. linq; using System. web; using System. web. UI; using System. web. UI. webControls; using System. web. script. serialization; namespace test2 {public partial class WebForm6: System. web. UI. page {public class Personnel {public int Id {get; set;} public string Name {get; set ;}} protected void Page_Load (object sender, EventArgs e) {Personnel personnel = new Personnel (); personnel. id = 1; personnel. name = ""; JavaScriptSerializer jsonSerializer = new JavaScriptSerializer (); // execute serialization lgx. text = jsonSerializer. serialize (personnel); // output result: {"Id": 1, "Name": ""}}}}

You can use the ScriptIgnore attribute to mark public or public fields that are not serialized.

        public class Personnel        {            [ScriptIgnore]            public int Id { get; set; }            public string Name { get; set; }        }

Output result: {"Name": ""}

2. JSON deserialization

Using system; using system. collections. generic; using system. LINQ; using system. web; using system. web. ui; using system. web. UI. webcontrols; using system. web. script. serialization; namespace Test2 {public partial class webform6: system. web. UI. page {public class personnel {public int ID {Get; set;} public string name {Get; Set ;}} protected void page_load (Object sender, eventargs E) {personnel = new personnel (); personnel. id = 1; personnel. name = ""; javascriptserializer jsonserializer = new javascriptserializer (); // execute serialized string it = jsonserializer. serialize (Personnel); // output result: {"ID": 1, "name": ""} personnel _ personnel = jsonserializer. deserialize <personnel> (it); lgx. TEXT = "ID" + _ personnel. id. tostring () + "name" + _ personnel. name ;}}}

 

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.