3

我正在使用 ASP.NET MVC2,我有以下对象结构:

public class IDealer {
  string Name { get; set; }
  List<IVehicle> Vehicles { get; set; }
}

public class DealerImpl {
  public string Name { get; set; }
  public List<IVehicle> Vehicles { get; set; }
}

public interface IVehicle {
    string Type { get; }
}

public class Car : IVehicle {
    public string Type { get { return this.GetType().FullName; } }
}

public class Truck : IVehicle {
    public string Type { get { return this.GetType().FullName; } }
}

我有以下类作为我的 ModelBinder,它在我的页面请求中反序列化对象:

public class JsonModelBinder : DefaultModelBinder {
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
        return deserialize(controllerContext, bindingContext);
    }

    protected static bool IsJSONRequest(ControllerContext controllerContext) {
        var contentType = controllerContext.HttpContext.Request.ContentType;
        return contentType.Contains("application/json");
    }

    protected virtual object deserialize(ControllerContext controllerContext, ModelBindingContext bindingContext) {
        Type modelType = bindingContext.ModelMetadata.ModelType;

        bool isNotConcrete = bindingContext.ModelMetadata.ModelType.IsInterface || bindingContext.ModelMetadata.ModelType.IsAbstract;
        if (!IsJSONRequest(controllerContext)) {
            return base.BindModel(controllerContext, bindingContext);
        } else {
            var request = controllerContext.HttpContext.Request;
            var jsonStringData = new StreamReader(request.InputStream).ReadToEnd();
            if (isNotConcrete) {
                Dictionary<string, Object> result = JsonConvert.DeserializeObject<Dictionary<string, Object>>(jsonStringData);
                string type = result["Type"] as string;
                modelType = Type.GetType(type + ",MyCompany.Common");
            }

            return JsonConvert.DeserializeObject(jsonStringData, modelType, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });
        }       
    }
}

// ASP.NET MVC Controller
protected override void Initialize(System.Web.Routing.RequestContext requestContext) {
  base.Initialize(requestContext);
  ModelBinders.Binders.DefaultBinder = new JsonModelBinder();
}

[HttpPost]
public ActionResult addUpdateDealer(IDealer dealer) {
  // breaks before here with the error in the comment below
}

// and in the aspx page
<script>
var model = <%= JsonConvert.SerializeObject(Model, Formatting.None, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }) %>;
</script>

我遇到的问题是,当代码尝试反序列化 IVehicles 的子列表时,它不知道要实例化哪种类型的车辆。我在 IVehicle 上放置了一个名为“Type”的属性,可用于帮助确定要实例化哪个类,但我不确定什么/在哪里/如何提供覆盖来执行此检查。

4

1 回答 1

1

您的解决方案类似于 JSON.NET 现在内置的称为 TypeNameHandling。以下是关于它的发行说明

您的 JSON 消息将需要包含一个$type属性,该属性不会被反序列化,但会被反序列化器解释为要使用的具体类型。

于 2012-06-19T21:33:18.790 回答