2016-04-08 36 views
0

我想提出一个电话的WebAPI得到一个对象返回与此类似:为什么我的ICollection的项目<Interface>从WebAPI调用中为空?

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

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

的ID和其他属性正确填充。 SubCategories prop具有正确大小的集合,但每个条目都为空。

任何想法为什么?我无法使它成为具体类型的集合(不在我的控制之下),但WebAPI能够找出它应该是哪个类...

+0

您如何期望WebAPI知道要将哪种类型的对象创建到SubCategories集合中? – StriplingWarrior

+2

我不明白这个说法:'我不能把它作为一个具体类型的集合(不受我控制),但WebAPI能够找出它应该是哪个类......'我认为这* *是**你的问题,JSON解串器不能反序列化为接口,除非你告诉它如何,否则它不能只搜索所有类型以试图找出要实例化的具体类。 – CodingGorilla

+0

@CodingGorilla我怎么去告诉它如何反序列化? –

回答

1

此答案假定您使用JSON.net这是ASP.NET WebAPI的默认值。由于JSON.net不知道如何创建IDocumentCategoryTree的具体实例,因此无法为您自动反序列化。所以,你需要做到这一点youself,顺便会做到这一点是使用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 
    } 
} 

这是一个非常简单的和不完整的例子给你出个主意,你如何能做到这一点并让你开始。你可以从这里开始阅读更多关于JsonConverter的其他SO帖子:How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

+0

我最终做了类似的事情。我使用JsConfig .RawDeserializeFn =(value)=> {return JsonSerializer.DeserializeFromString (value);}; 但是,当我得到一些深层次的值时,这些值再次为空。 –

0

XML和JSON序列化/反序列化应该用混凝土类。如果它没有具体的,它不会知道如何正确地序列化它。我建议创建一个具体的IDocumentCategoryTree,像DocumentCatTreeApiModel。这将允许序列化过程正常工作。

相关问题