-1
工作,我需要使用自定義的Json解串器我已經做了下一個:JSON NET自定義解串器並不
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行動網站的所有字段爲空。爲什麼會發生?
你可以[編輯]你的問題提供[mcve]嗎?特別是'BindModel'中'string json'變量的內容會有幫助。 – dbc
@dbc感謝您的鏈接,順便說一句,今天我解決了它。問題出在我的aja調用中,我以這種方式發送數據'$ .ajax {data:{site:getSite()}',當我用'$ ajax {data:{getSite}}替換它時,它就變成了工作。我不知道詳細信息,但它很有用,我很高興)))) – Nikita
您可以將解決方案作爲答案添加,然後接受它,以便此問題不會顯示在「未答覆」選項卡中。 – cyrotello