Cannot deserialize JSON array into type – Json.NET

You have to write a custom JsonConverter:

    public class CountryModelConverter : JsonConverter
    {

        public override bool CanConvert(Type objectType)
        {
            if (objectType == typeof(CountryModel))
            {
                return true;
            }

            return false;
        }

        public override object ReadJson(JsonReader reader, Type objectType
            , object existingValue, JsonSerializer serializer)
        {
            reader.Read(); //start array
            //reader.Read(); //start object
            JObject obj = (JObject)serializer.Deserialize(reader);

            //{"page":1,"pages":1,"per_page":"50","total":35}
            var model = new CountryModel();

            model.Page = Convert.ToInt32(((JValue)obj["page"]).Value);
            model.Pages = Convert.ToInt32(((JValue)obj["pages"]).Value);
            model.Per_Page = Int32.Parse((string) ((JValue)obj["per_page"]).Value);
            model.Total = Convert.ToInt32(((JValue)obj["total"]).Value);

            reader.Read(); //end object

            model.Countries = serializer.Deserialize<List<Country>>(reader);

            reader.Read(); //end array

            return model;
        }

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

And tag the CountryModel with that converter (I also had to switch some int to string):

    [JsonConverter(typeof(CountryModelConverter))]
    public class CountryModel
    {
        public int Page { get; set; }
        public int Pages { get; set; }
        public int Per_Page { get; set; }
        public int Total { get; set; }

        public List<Country> Countries { get; set; }
    }

    public class Country
    {
        public string Id { get; set; }
        public string Iso2Code { get; set; }
        public string Name { get; set; }
        public Region Region { get; set; }
    }

    public class Region
    {
        public string Id { get; set; }
        public string Value { get; set; }
    }

Then you should be able to deserialize like this:

var output = JsonConvert.DeserializeObject<CountryModel>(result);

Leave a Comment