JSON NET自定义反序列化器根本不起作用

时间:2016-08-13 22:54:29

标签: c# json asp.net-mvc json.net

我需要使用自定义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;
        }
    }

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行动

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动作站点中,所有字段都为null。为什么会这样?

1 个答案:

答案 0 :(得分:1)

问题在于我发送数据的方式。因此,当您需要为默认模型绑定器发送数据时,请使用以下命令:

$.ajax({
    ...
    data:{variableName: jsonValue}
}

默认绑定器将正确工作,他足够聪明,但现在我的SiteModelBinder读取整个输入流我用这个替换数据:

$.ajax({
    data: jsonValue
}

并且所有都变得有效,所以问题是variableName也是我尝试解析并导致错误的json的一部分。