我正在学习 JSON。我要做的就是发回一些数据并将其转换为.NET 对象。
我一直在尝试不同的教程,我想我有点理解它。下面是我的代码。我不明白的是,请求对象中保存 Json 数据的内容是什么,我如何反序列化它?
我的 Javascript
$(function () {
// Do your stuff here
alert("wööööö");
urlToHandler = 'JSonTestHandler.ashx';
jsonData = '{ "FavoriteFood":"Pasta with butter and cheese", "FavoriteSport": "Submission Wrestling", "FavoriteGame": "Starcraft 2", "FavoriteMusic": "Hip Hop" }';
$.ajax({
url: urlToHandler,
data: jsonData,
dataType: 'json',
type: 'POST',
contentType: 'application/json',
success: function (data) {
setAutocompleteData(data.responseDateTime);
},
error: function (data, status, jqXHR) {
alert('There was an error.');
}
}); // end $.ajax
});
我的 JSON 处理程序
[WebService(Namespace = "http://localhost:53243")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class JSonTestHandler : IHttpHandler, System.Web.SessionState.IReadOnlySessionState
{
public void ProcessRequest(HttpContext context)
{
var json = new JavaScriptSerializer();
var memoryStream = new MemoryStream();
var serializer = new DataContractJsonSerializer(typeof(PersonalPreferences));
memoryStream.Position = 0;
var personalPreferenceFromJson = (PersonalPreferences)serializer.ReadObject(memoryStream);
}
public bool IsReusable
{
get
{
return false;
}
}
}
保存 Json 数据的我的对象
[DataContract]
public class PersonalPreferences
{
[DataMember]
public string FavoriteFood { get; set; }
[DataMember]
public string FavoriteSport { get; set; }
[DataMember]
public string FavoriteGame { get; set; }
[DataMember]
public string FavoriteMusic { get; set; }
public PersonalPreferences()
{
}
}