gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:59:32 24 4
gpt4 key购买 nike

我正在使用 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属性,它不会被反序列化,但会被反序列化器解释为要使用的具体类型。

关于json - 如何反序列化接口(interface)的子列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11109641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com