如何在JSON . NET的帮助下从请求中读取对象
本文关键字:请求 读取 取对象 帮助 JSON NET | 更新日期: 2023-09-27 18:02:14
我需要使用JSON . NET序列化器。
SiteModelBinder
internal class SiteModelBinder : System.Web.Mvc.IModelBinder
{
public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
{
// use Json.NET to deserialize the incoming Position
controllerContext.HttpContext.Request.InputStream.Position = 0; // see: http://stackoverflow.com/a/3468653/331281
Stream stream = controllerContext.RequestContext.HttpContext.Request.InputStream;
var readStream = new StreamReader(stream, Encoding.UTF8);
string json = readStream.ReadToEnd();
return JsonConvert.DeserializeObject<Site>(json, new JsonBuildBlockConverter());
}
}
这里我得到了一个异常在位置0,0处无法识别的字符
return JsonConvert.DeserializeObject<Site>(json, new JsonBuildBlockConverter());
ajax调用$.ajax({
url: '/Site/Update',
data: { site: getSite() },
contentType: 'application/json',
method: 'POST',
success: function (data) {
console.log('Success save');
},
error: function (data) {
debugBox(data);
}
});
和mvc动作,BTW BuildBlocks属性类型是List<AbstractBuildBlock>
和TextBlock
派生。
public string Update(Site site)
{
//the goal to see in debugger that block is not null after the next line
TextBlock block = site.Pages[0].Rows[0].BuildBlocks[0] as TextBlock;
//siteRepository.Add(site);
return "Success";
}
我错过了什么或做错了什么?
正确的ajax调用
$.ajax({
type: "POST",
url: "/Site/Update",
dataType: "json",
data: {JSON.stringify(filtersData) }, //without name because I'll use custom ModelBinder
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (data) {
alert("ok");
},
error:function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});