Home > Web Front-end > JS Tutorial > Json serialization and deserialization method analysis_jquery

Json serialization and deserialization method analysis_jquery

WBOY
Release: 2016-05-16 17:08:08
Original
1430 people have browsed it

Copy code The code is as follows:

///
/Json serialization, which is used to send to the client
/// & lt;/Summary & gt;
Public Stration 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();

         }

}

                                                                                        ​;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



Copy code The code is as follows: [DataContract]
public class TestObj
{
[DataMember]
public string make { get; set; }
public string model { get; set ; }
                                                                                                                                                               ,                                                                                                           ; >------------------javascript gets Json--------------------

javascript calls test code




Copy code

The code is as follows:

$('#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#后台生成代码
复制代码 代码如下:

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;
            }
        }
}

//返回值为 {"color":"Color is Value","make":"Make is Value","model":"Model is Value","year":999}


-----------------C#由Json生成对象-----------------------

javascript调用测试代码

复制代码 代码如下:

           $('#postJson').click(function() {

                var m_obj = { make: "Dodge", model: "Coronet R/T", year: 1968, color: "yellow" };
                var jsonStr = JSON.stringify(m_obj); //用Json2.js生成Json字符串

                $.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#后台生成代码
复制代码 代码如下:

public class postJsonHandler: IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string jsonStr = context.Request["postjson"];

            TestObj obj = jsonStr.FromJsonTo();

            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;
            }
        }
}


使用Json时需要注意,服务器端拼凑生成Json字符串时,一定要注意把字符串用""包裹,不然客户端接收时肯定会报错,根据Json字符串生成对象,是根据对应的名称赋值,多于或少于都不会报错.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template