快速业务通道

jquery, json与ashx的完美结合

作者 佚名技术 来源 NET编程 浏览 发布时间 2012-04-11
p;      Encoding.UTF8.GetBytes(data));

            var result = (T)serializer.ReadObject(ms);
            ms.Close();
            return result;
        }
        /// <summary>
        /// 将任何一个对象转换为JSON字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJsonString<T>(this T obj) {
            var serializer = new DataContractJsonSerializer(typeof(T));
            var ms = new MemoryStream();
            serializer.WriteObject(ms, obj);
            ms.Position = 0;
            var result = Encoding.UTF8.GetString(ms.GetBuffer());
            ms.Close();
            return result;
        }
    }

这样,在ashx里面的代码就很简单了

 var emp = context.Request["data"].ToJsonObject<Employee>();
            var result = new ActionResult() { Code = 200, Message = "成功" };
            context.Response.Write(result.ToJsonString());

不错吧,这样以后处理Json就是如此容易