I need to use custom Json deserialiser I've done the next:
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;
}
}
Model Binder
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 action
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";
}
I have set up break points in SiteModelBinder and JsonBuildBlockConverter. I go into SiteModelBinder but don't go to JsonBuildBlockConverter. And in mvc action site has all fields null. Why it happens?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…