Json序列化和反序列化方法解析(2)

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字符串生成对象,是根据对应的名称赋值,多于或少于都不会报错.

您可能感兴趣的文章:

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

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