欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Json序列化和反序列化方法解析

程序员文章站 2022-06-19 21:46:06
代码如下:  ///         /// json序列化...

代码如下:


 /// <summary>
        /// json序列化,用于发送到客户端
        /// </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反序列化,用于接收客户端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;

        }


实体类

. 代码如下:


    [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获取json--------------------

 

javascript调用测试代码

. 代码如下:


$('#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<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;
            }
        }
}


使用json时需要注意,服务器端拼凑生成json字符串时,一定要注意把字符串用\"\"包裹,不然客户端接收时肯定会报错,根据json字符串生成对象,是根据对应的名称赋值,多于或少于都不会报错。