为什么我的ICollection&LT的物品;接口>从电话的WebAPI空? [英] Why are the items of my ICollection<Interface> null from a WebAPI call?

查看:109
本文介绍了为什么我的ICollection&LT的物品;接口>从电话的WebAPI空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提出一个电话的WebAPI得到一个对象返回类似这样的:

I am making a WebAPI call to get an object back similar to this one:

public class DocumentCategoryModel : IDocumentCategoryTree
    {
        public DocumentCategoryModel()
        {
            SubCategories = new List<IDocumentCategoryTree>();
        }

        public int ID { get; set; }
        public ICollection<IDocumentCategoryTree> SubCategories { get; set; }
    }

该ID和其他属性都无误。子类别支撑具有正确尺寸的集合,但每个条目为空。

The ID and other properties are populated correctly. The SubCategories prop has a collection of the correct size, but every entry is null.

任何想法,为什么?我不能让一个具体类型的集合(我的控制),但的WebAPI能够弄清楚它应该是哪一个类...

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...

推荐答案

这答案假设您正在使用 JSON.net 这与ASP.NET的WebAPI默认。由于JSON.net不知道如何创建 IDocumentCategoryTree 的具体实例,它不能反序列化自动为您。所以,你需要这样做youself,路上的 I 的会做这是在使用JsonConverter为你的类:

This answer assumes you're using JSON.net which is the default with ASP.NET WebAPI. Since JSON.net doesn't understand how to create a concrete instance of IDocumentCategoryTree it cannot deserialize that automatically for you. So you will need to do this youself, the way I would do this is using a JsonConverter for your class:

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
    }
}

这是一个非常简单的和不完整的例子给你出个主意,你如何能做到这一点,让你开始。你可以阅读更多有关 JsonConverter S IN从这里开始,其他一些职位的SO:<一href=\"http://stackoverflow.com/questions/8030538/how-to-implement-custom-jsonconverter-in-json-net-to-deserialize-a-list-of-base\">How在JSON.NET实现自定义JsonConverter反序列化基类对象的列表?。

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 JsonConverters in some other SO posts starting here: How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?.

这篇关于为什么我的ICollection&LT的物品;接口&GT;从电话的WebAPI空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆