[英]Why are the items of my ICollection<Interface> null from a WebAPI call?
I am making a WebAPI call to get an object back similar to this one: 我正在进行WebAPI调用以返回与该对象相似的对象:
public class DocumentCategoryModel : IDocumentCategoryTree
{
public DocumentCategoryModel()
{
SubCategories = new List<IDocumentCategoryTree>();
}
public int ID { get; set; }
public ICollection<IDocumentCategoryTree> SubCategories { get; set; }
}
The ID and other properties are populated correctly. 正确填充了ID和其他属性。 The SubCategories prop has a collection of the correct size, but every entry is null. SubCategories属性具有正确大小的集合,但每个条目均为null。
Any idea why? 知道为什么吗? I can't make it a collection of a concrete type (out of my control), but the WebAPI is able to figure out which class it should be... 我无法使其成为具体类型的集合(在我的控制范围内),但是WebAPI能够确定它应该是哪个类...
This answer assumes you're using JSON.net which is the default with ASP.NET WebAPI. 该答案假定您使用的是JSON.net ,这是ASP.NET WebAPI的默认设置。 Since JSON.net doesn't understand how to create a concrete instance of IDocumentCategoryTree
it cannot deserialize that automatically for you. 由于JSON.net无法理解如何创建IDocumentCategoryTree
的具体实例,因此它无法为您自动反序列化。 So you will need to do this youself, the way I would do this is using a JsonConverter for your class: 因此,您需要自己执行此操作, 我执行此操作的方法是为您的类使用JsonConverter:
public class DocumentCategoryModel : IDocumentCategoryTree
{
public DocumentCategoryModel()
{
SubCategories = new List<IDocumentCategoryTree>();
}
public int ID { get; set; }
[JsonConverter(typeof(DocumentCategoryTreeConverter)]
public ICollection<IDocumentCategoryTree> SubCategories { get; set; }
}
public class DocumentCategoryTreeConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// Todo if desired
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return serializer.Deserialize<TestTree>(reader);
}
public override bool CanConvert(Type objectType)
{
// Todo
}
}
This is a very simplistic and incomplete example to give you an idea how you can do this and get you started. 这是一个非常简单且不完整的示例,目的是使您了解如何执行此操作并入门。 You can read more about JsonConverter
s in some other SO posts starting here: How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects? 您可以从以下其他SO文章中了解有关JsonConverter
的更多信息: 如何在JSON.NET中实现自定义JsonConverter以反序列化基类对象列表? . 。
XML and JSON serialization/deserializtion should be happening with concrete classes. XML和JSON序列化/反序列化应在具体类中进行。 If it doesn't have a concrete it won't know how to properly serialize it. 如果没有具体的内容,它将不知道如何正确地序列化它。 I suggest creating a concrete for IDocumentCategoryTree
, something like DocumentCatTreeApiModel
. 我建议为IDocumentCategoryTree
创建一个具体的DocumentCatTreeApiModel
,例如DocumentCatTreeApiModel
。 That will allow for the serialization process to work properly. 这将允许序列化过程正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.