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;
}
javascript调用测试代码
alert(result.make);
alert(result.model);
alert(result.year);
alert(result.color);
}
});
});
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}
javascript调用测试代码
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);
}
});
});
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;
}
}
}
新闻热点
疑难解答