json - 如何反序列化接口(interface)的子列表?

我正在使用 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”的属性,可用于帮助确定要实例化哪个类,但我不确定什么/在哪里/如何提供覆盖来执行此检查。

最佳答案

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

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

https://stackoverflow.com/questions/11109641/

相关文章:

hudson - Jenkins jacoco插件

r - 提取数据框中每个元素的前n个值的索引

perl - Perl的system()是否自动在Cygwin中转义字符?

hibernate - Grails/hibernate 标准ID inList

codeigniter - CodeIgniter DB session 问题:sess_expir

assembly - 如何从CUDA C调用ptx函数?

ruby-on-rails-3 - 回形针在使用S3时在本地查找文件以进行重新处理

web-services - 使用Web服务访问TFS

hibernate - Jpa vs Hibernate - 标准还是功能?

perl - 从 Mojolicious 用户代理响应中提取 cookie