title: NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>
body: <p>I am trying to move some code to consume ASP.NET MVC Web API generated Json data instead of SOAP Xml.</p>
  
  <p>I have run into a problem with serializing and deserializing properties of type:</p>
  
  <pre><code>IEnumerable&lt;ISomeInterface&gt;.
  </code></pre>
  
  <p>Here is a simple example:</p>
  
  <pre><code>public interface ISample{
    int SampleId { get; set; }
  }
  public class Sample : ISample{
    public int SampleId { get; set; }
  }
  public class SampleGroup{
    public int GroupId { get; set; }
    public IEnumerable&lt;ISample&gt; Samples { get; set; }
   }
  }
  </code></pre>
  
  <p>I can serialize instances of SampleGroup easily with:</p>
  
  <pre><code>var sz = JsonConvert.SerializeObject( sampleGroupInstance );
  </code></pre>
  
  <p>However the corresponding deserialize fails:</p>
  
  <pre><code>JsonConvert.DeserializeObject&lt;SampleGroup&gt;( sz );
  </code></pre>
  
  <p>with this exception message:</p>
  
  <p>"Could not create an instance of type JsonSerializationExample.ISample. Type is an interface or abstract class and cannot be instantated."</p>
  
  <p>If I derive a JsonConverter I can decorate my property as follows:</p>
  
  <pre><code>[JsonConverter( typeof (SamplesJsonConverter) )]
  public IEnumerable&lt;ISample&gt; Samples { get; set; }
  </code></pre>
  
  <p>Here is the JsonConverter: </p>
  
  <pre><code>public class SamplesJsonConverter : JsonConverter{
    public override bool CanConvert( Type objectType ){
      return ( objectType == typeof (IEnumerable&lt;ISample&gt;) );
    }
  
    public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer ){
      var jA = JArray.Load( reader );
      return jA.Select( jl =&gt; serializer.Deserialize&lt;Sample&gt;( new JTokenReader( jl ) ) ).Cast&lt;ISample&gt;( ).ToList( );
    }
  
    public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer ){
      ... What works here?
    }
  }
  </code></pre>
  
  <p>This converter solves the deserialization problem but I cannot figure how to code the WriteJson method to get serialization working again.</p>
  
  <p>Can anybody assist?  </p>
  
  <p>Is this a "correct" way to solve the problem in the first place?</p>