如何反序列化子接口列表?

时间:2012-06-19 21:21:36

标签: json asp.net-mvc-2 serialization json.net

我正在使用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>

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

1 个答案:

答案 0 :(得分:1)

您的解决方案类似于JSON.NET现在内置的,称为TypeNameHandling。 Here are the release notes on that

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

相关问题