我需要使用自定义Json反序列化器,我已经做了下一步:
JsonCreationConverter
public abstract class AbstractJsonCreationConverter<T> : JsonConverter
{
protected abstract T Create(Type objectType, JObject jsonObject);
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
var jsonObject = JObject.Load(reader);
var target = Create(objectType, jsonObject);
serializer.Populate(jsonObject.CreateReader(), target);
return target;
}
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
JsonBuildBlockConverter
protected override AbstractBuildBlock Create(Type objectType, JObject jsonObject)
{
var type = jsonObject["contentType"].ToString();
switch(type)
{
case "text":
return new TextBlock();
default:
return null;
}
}
模型绑定器
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());
}
mvc行动public string Update(Site site)
{
//the goal to see in debugger block not null after next line
TextBlock block = site.Pages[0].Rows[0].BuildBlocks[0] as TextBlock;
//siteRepository.Add(site);
return "Success";
}
我在SiteModelBinder和JsonBuildBlockConverter中设置了断点。我去SiteModelBinder,但不去JsonBuildBlockConverter。而在mvc中,action site的所有字段都是null。为什么会这样?
问题在于我发送数据的方式。因此,当您需要为默认模型绑定器发送数据时,请使用:
$.ajax({
...
data:{variableName: jsonValue}
}
默认绑定将正确地工作,他是足够聪明,但现在我的SiteModelBinder,因为它读取整个输入流,我用这个替换数据:
$.ajax({
data: jsonValue
}
和所有变得工作,所以问题是,variableName也是json的一部分,我试图解析并导致错误。