How to populate item of customized list in JsonConverter.

Sep 30, 2009 at 4:35 AM

Hi

i have a customized collection with abstract class type as item:

public class MyCollection: List<AbsClass>

{ ...}

public class SubClass1: AbsClass {}

public class SubClass2: AbsClass {}

And i defined a JsonConverter for it.

public class MyCollectionJsonConverter : JsonConverter

{

 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)

 {

   MyCollection collection = value as MyCollection;

   writer.WriteStartArray();

   foreach(AbsClass item in collection)

   {     serializer.Serialize(writer, item);   }

   writer.WriteEndArray();

 }


 public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)

 {

  //Here i don't know how to populate item form reader. Are there some build-in methods i can use?

 }


 public override bool CanConvert(Type objectType)

 {

   return (objectType.Equals(typeof(SubClass1) || objectType.Equals(typeof(SubClass2));

 }

}

Thanks.

Coordinator
Oct 3, 2009 at 12:53 AM

Well you would call reader.Read to move past the start of the array and then serializer.Deserializer on each of the contents of the array.