Custom JSON converter for Json.NET

Ever had problem with JSON data sometimes array and sometimes object that will cause the deserialization process to fail? Anyway, if you´re to encounter this “phenomenon” it is possible to handle building a custom JsonConverter that inherits the abstract Newtonsoft.Json.JsonConverter class.

using Newtonsoft.Json;
using System;

public class CustomJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(MyObject).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.StartArray)
        {
            return serializer.Deserialize<MyObject[]>(reader);
        }
        else
        {
            var myObject = serializer.Deserialize<MyObject>(reader);
            return new MyObject[] { myObject };
        }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Usage:

[JsonConverter(typeof(CustomJsonConverter))]
public MyObject[] MyProperty { get; set; }

And:

var myObject = JsonConvert.DeserializeObject<MyObject[]>(jsonString, new CustomJsonConverter(typeof(MyObject)));