Parsing of JSON serialization and deserialization methods

Source: Internet
Author: User
Tags bool json serialization

  This article is mainly on the JSON serialization and deserialization methods are introduced, the need for friends can come to the reference, I hope to be helpful to everyone

  Code as follows:  ///<summary>        ///JSON serialization for sending to client        ///&L t;/summary>         public static string Tojsjson (This object item)         {& nbsp             DataContractJsonSerializer serializer = new DataContractJsonSerializer (item. GetType ());               using (MemoryStream ms = new MemoryStream ())             {                  serializer. WriteObject (MS, item);                   StringBuilder sb = new StringBuilder ();                   SB. Append (Encoding.UTF8.GetString) (Ms. ToArray ()));                   return SB. ToString ();               &nbsp        ; {         ///<summary>        ///JSON deserialization to generate the corresponding object after receiving the client JSON &nbs P      ///</summary>         public static T fromjsonto<t> (This string JSON String)         {              DataContractJsonSerializer ser = NE W DataContractJsonSerializer (typeof (T));               MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (jsonstring));               T jsonobject = (t) ser. ReadObject (MS);               Ms. Close ();               return jsonobject;          }      entity class code as follows:     [DataContract]     public class Testobj     {        [DataMember]         public string make {get; SE T } &NBsp       [DataMember]         public string model {get; set;}       &NBSP ; [DataMember]         public int year {get; set;}         [DataMember]   &NB Sp     public string color {get; set;}    }  ------------------JavaScript gets JSON----------------- ---  javascript invoke test code     code as follows: $ (' #getJson '). Click (function () {                $.ajax ({                    URL: "Getjsonhandler.ashx", & nbsp                   type: ' Get ',             &NBS P       data: {},                     DataType: ' JSON ', &NB Sp                   timeout:1000,             &NBsp       error:function (XMLHttpRequest, Textstatus, Errorthrown) {alert (Textstatus)},                     success:function (result) {            &NB Sp             alert (result.make);                         alert (Result.model);                         alert (result.year);                         alert (result.color);                                   & nbsp  });            });     C # background generated code is as follows: public class Getjsonhandler:ihttphandler     {public void ProcessRequest Httpcont Ext context)         {           Testobj obj = new Testobj ();               Obj.make = "Make is Value";             Obj.model = "model is Value";             obj.year = 999;             Obj.color = "color is Value";               context. Response.Write (obj. Tojsjson ());        }  public bool isreusable         {        &NBSP ;   Get             {                Fals E            }        }  //return value {' Color ': ' Color is value ', ' make ' : ' Make is value ', ' model ': ' model is value ', ' Year ': 999}    -----------------C # Object generated by JSON-----------------------  JavaScript call test code     code as follows:            $ (' #posTjson '). Click (function () {                  var m_obj = {make: "Dodge", MoD El: "Coronet r/t", year:1968, Color: "Yellow"};                 var jsonstr = json.stringify (m_obj); Generate JSON strings with json2.js                   $.ajax ({        & nbsp           URL: "Postjsonhandler.ashx",                 &N Bsp   Type: ' POST ',                     data: {POSTJSON:JSONSTR}, &N Bsp                   DataType: ' json ',                     timeout:1000,                     ERROR:F Unction (XMLHttpRequest, Textstatus, Errorthrown) {alert (Textstatus)},           &NBsp         success:function (result) {                  &NB Sp       alert (result.success);                                   & nbsp  }); });     C # background generated code is as follows: public class Postjsonhandler:ihttphandler     {        Public void ProcessRequest (HttpContext context)         {            String J Sonstr = context. request["Postjson"];               Testobj obj = jsonstr.fromjsonto<testobj> ();               if (string. IsNullOrEmpty (obj.make) | | String. IsNullOrEmpty (Obj.model) | | String. IsNullOrEmpty (obj.color)     | | Obj.year < 0)             {                Conte Xt. RespoNse. Write ("{success:false}");                         else         &NB Sp   {                context. Response.Write ("{success:true}");             {  public bool isreusable         {    &NBS P       Get             {              &NBS P return false;            }        }     When using JSON you need to be aware that server-side patchwork generation of JSON strings must be Note that the string is "" wrapped, otherwise the client will certainly receive an error, according to the JSON string to generate the object, based on the corresponding name assignment, more or less than the error.
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.