近来在研究jQuery,用$.ajax在与后台交换数据时用到Json格式,后台与前台序列化和反序列化方法研究了很久才成功,发文共享.
前台调用的JS文件需要用到jQuery-1.2.6.js和json2.js(http://www.json.org/json2.js),后台引用空间System.Runtime.Serialization和System.Runtime.Serialization.Json
Json序列化和反序列化方法
///
<summary>
Json序列化,用于发送到客户端
</summary>
public static string ToJsJson( this object item)
{
DataContractJsonSerializerserializer = new DataContractJsonSerializer(item.GetType());
using (MemoryStreamms MemoryStream())
{
serializer.WriteObject(ms,item);
StringBuildersb StringBuilder();
sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
return sb.ToString();
}
}
Json反序列化,用于接收客户端Json后生成对应的对象
TFromJsonTo < T > ( jsonString)
{
DataContractJsonSerializerser DataContractJsonSerializer( typeof (T));
MemoryStreamms MemoryStream(Encoding.UTF8.GetBytes(jsonString));
TjsonObject (T)ser.ReadObject(ms);
ms.Close();
jsonObject;
}
Json序列化,用于发送到客户端
</summary>
public static string ToJsJson( this object item)
{
DataContractJsonSerializerserializer = new DataContractJsonSerializer(item.GetType());
using (MemoryStreamms MemoryStream())
{
serializer.WriteObject(ms,item);
StringBuildersb StringBuilder();
sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
return sb.ToString();
}
}
Json反序列化,用于接收客户端Json后生成对应的对象
TFromJsonTo < T > ( jsonString)
{
DataContractJsonSerializerser DataContractJsonSerializer( typeof (T));
MemoryStreamms MemoryStream(Encoding.UTF8.GetBytes(jsonString));
TjsonObject (T)ser.ReadObject(ms);
ms.Close();
jsonObject;
}
实体类
[DataContract]
class TestObj
{
[DataMember]
make{ get ; set ;}
[DataMember]
model{ int year{ color{ ;}
}
class TestObj
{
[DataMember]
make{ get ; set ;}
[DataMember]
model{ int year{ color{ ;}
}
--------------------------------------------javascript获取Json---------------------------------
$(
'
#getJson
).click(
function
(){
$.ajax({
url: " getJsonHandler.ashx ,
type: GET json 1000 (XMLHttpRequest,textStatus,errorThrown){alert(textStatus)},
success: (result){
alert(result.make);
alert(result.model);
alert(result.year);
alert(result.color);
}
});
});
$.ajax({
url: " getJsonHandler.ashx ,
type: GET json 1000 (XMLHttpRequest,textStatus,errorThrown){alert(textStatus)},
success: (result){
alert(result.make);
alert(result.model);
alert(result.year);
alert(result.color);
}
});
});
getJsonHandler:IHttpHandler
{
void ProcessRequest(HttpContextcontext)
{
TestObjobj TestObj();
obj.make " MakeisValue ;
obj.model ModelisValue ;
obj.year 999 ;
obj.color ColorisValue ;
context.Response.Write(obj.ToJsJson());
}
bool IsReusable
{
{
false ;
}
}
}
// 返回值为{"color":"ColorisValue","make":"MakeisValue","model":"ModelisValue","year":999}
{
void ProcessRequest(HttpContextcontext)
{
TestObjobj TestObj();
obj.make " MakeisValue ;
obj.model ModelisValue ;
obj.year 999 ;
obj.color ColorisValue ;
context.Response.Write(obj.ToJsJson());
}
bool IsReusable
{
{
false ;
}
}
}
// 返回值为{"color":"ColorisValue","make":"MakeisValue","model":"ModelisValue","year":999}
---------------------------------C#由Json生成对象---------------------------------------
#postJson
(){
var m_obj {make: Dodge CoronetR/T 1968 yellow };
jsonStr JSON.stringify(m_obj); 用Json2.js生成Json字符串
$.ajax({
url: postJsonHandler.ashx POST (result){
alert(result.success);
}
});
});
var m_obj {make: Dodge CoronetR/T 1968 yellow };
jsonStr JSON.stringify(m_obj); 用Json2.js生成Json字符串
$.ajax({
url: postJsonHandler.ashx POST (result){
alert(result.success);
}
});
});
postJsonHandler:IHttpHandler
{
ProcessRequest(HttpContextcontext)
{
context.Request[ postjson ];
TestObjobj jsonStr.FromJsonTo TestObj ();
if .IsNullOrEmpty(obj.make) || .IsNullOrEmpty(obj.model) .IsNullOrEmpty(obj.color)
obj.year 0 )
{
context.Response.Write( {success:false} );
}
else
{
context.Response.Write( {success:true} );
}
;
}
}
}
使用Json时需要注意,服务器端拼凑生成Json字符串时,一定要注意把字符串用/"/"包裹,不然客户端接收时肯定会报错,根据Json字符串生成对象,是根据对应的名称赋值,多于或少于都不会报错.{
ProcessRequest(HttpContextcontext)
{
context.Request[ postjson ];
TestObjobj jsonStr.FromJsonTo TestObj ();
if .IsNullOrEmpty(obj.make) || .IsNullOrEmpty(obj.model) .IsNullOrEmpty(obj.color)
obj.year 0 )
{
context.Response.Write( {success:false} );
}
else
{
context.Response.Write( {success:true} );
}
;
}
}
}