Json serialization and deserialization method parsing

  • 2020-03-30 00:56:31
  • OfStack


 /// <summary>
        /// Json serialization for sending to the client
        /// </summary>
        public static string ToJsJson(this object item)
        {
            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();
            }
        }
        /// <summary>
        /// Json deserialization, used to generate the corresponding object after receiving the client Json
        /// </summary>
        public static T FromJsonTo<T>(this string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T jsonObject = (T)ser.ReadObject(ms);
            ms.Close();
            return jsonObject;
        } 

Entity class

    [DataContract]
    public class TestObj
    {
        [DataMember]
        public string make { get; set; }
        [DataMember]
        public string model { get; set; }
        [DataMember]
        public int year { get; set; }
        [DataMember]
        public string color { get; set; }
    }

-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- javascript access Json -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

Javascript calls the test code


$('#getJson').click(function() {
                $.ajax({
                    url: "getJsonHandler.ashx",
                    type: 'GET',
                    data: {},
                    dataType: 'json',
                    timeout: 1000,
                    error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus) },
                    success: function(result) {
                        alert(result.make);
                        alert(result.model);
                        alert(result.year);
                        alert(result.color);
                    }
                });
            });

C# generates code behind the scenes

public class getJsonHandler: IHttpHandler
    {
public void ProcessRequest(HttpContext 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
        {
            get
            {
                return false;
            }
        }
}
//Return Value {"color":" color is Value","make":" make is Value","model":" model is Value","year":999}

-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- c # is generated by a Json object -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

Javascript calls the test code


           $('#postJson').click(function() {
                var m_obj = { make: "Dodge", model: "Coronet R/T", year: 1968, color: "yellow" };
                var jsonStr = JSON.stringify(m_obj); //Json2.js is used to generate Json strings
                $.ajax({
                    url: "postJsonHandler.ashx",
                    type: 'POST',
                    data: { postjson: jsonStr },
                    dataType: 'json',
                    timeout: 1000,
                    error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus) },
                    success: function(result) {
                        alert(result.success);
                    }
                });
});

C# generates code behind the scenes

public class postJsonHandler: IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string jsonStr = context.Request["postjson"];
            TestObj obj = jsonStr.FromJsonTo<TestObj>();
            if (string.IsNullOrEmpty(obj.make) || string.IsNullOrEmpty(obj.model) || string.IsNullOrEmpty(obj.color) 
|| obj.year < 0)
            {
                context.Response.Write("{success:false}");
            }
            else
            {
                context.Response.Write("{success:true}");
            }
public bool IsReusable
        {
            get
            {
                return false;
            }
        }
}

When using Json, we need to pay attention, when the server piece together the Json string, we must pay attention to the string with \"\" package, or the client will receive an error, according to the Json string generated object, is according to the corresponding name assignment, more or less will not report an error.


Related articles: