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() {

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdwgjj.html