stackoverflow.com/questions/49030516/how-can-i-ignore-this-blank-array-while-deserializing-in-c

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;


using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;	

    // https://stackoverflow.com/questions/49030516/how-can-i-ignore-this-blank-array-while-deserializing-in-c

    public class TolerantObjectCollectionConverter<TItem> : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return !objectType.IsArray && objectType != typeof(string) && typeof(ICollection<TItem>).IsAssignableFrom(objectType);
        }

        public override bool CanWrite { get { return false; } }

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

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // Get contract information
            var contract = serializer.ContractResolver.ResolveContract(objectType) as JsonArrayContract;
            if (contract == null || contract.IsMultidimensionalArray || objectType.IsArray)
                throw new JsonSerializationException(string.Format("Invalid array contract for {0}", objectType));

            // Process the first token
            var tokenType = reader.SkipComments().TokenType;
            if (tokenType == JsonToken.Null)
                return null;
            if (tokenType != JsonToken.StartArray)
                throw new JsonSerializationException(string.Format("Expected {0}, encountered {1} at path {2}", JsonToken.StartArray, reader.TokenType, reader.Path));

            // Allocate the collection
            var collection = existingValue as ICollection<TItem> ?? (ICollection<TItem>)contract.DefaultCreator();

            // Process the collection items
            while (reader.Read())
            {
                switch (reader.TokenType)
                {
                    case JsonToken.EndArray:
                        return collection;

                    case JsonToken.StartObject:
                    case JsonToken.Null:
                        collection.Add(serializer.Deserialize<TItem>(reader));
                        break;

                    default:
                        reader.Skip();
                        break;
                }
            }
            // Should not come here.
            throw new JsonSerializationException("Unclosed array at path: " + reader.Path);
        }
    }

    public static partial class JsonExtensions
    {
        public static JsonReader SkipComments(this JsonReader reader)
        {
            while (reader.TokenType == JsonToken.Comment && reader.Read())
                ;
            return reader;
        }
    }

    public class RootObject
    {
        [JsonProperty("total_events")]
        public int TotalEvents { get; set; }

        [JsonProperty("json.appID")]
        [JsonConverter(typeof(TolerantObjectCollectionConverter<JsonAppID>))]
        public List<JsonAppID> AppIds { get; set; }

        [JsonProperty("unique_field_count")]
        public int UniqueFieldCount { get; set; }
    }

    public class JsonAppID
    {
        [JsonProperty(PropertyName = "count")]
        public int Count { get; set; }

        [JsonProperty(PropertyName = "term")]
        public string Term { get; set; }
    }

    class TestClass
    {
        public static void Test()
        {
            foreach (var json in GetJson())
                Test(json);
            Console.WriteLine("\nTests passed.");
        }

        static void Test(string json)
        {
            Console.WriteLine("\nTesting JSON: ");
            Console.WriteLine(json);

            var result = JsonConvert.DeserializeObject<RootObject>(json);

            var json2 = JsonConvert.SerializeObject(result, Formatting.Indented);

            Console.WriteLine("Re-serialized result: ");
            Console.WriteLine(json2);

            Assert.IsTrue(JToken.Parse(json).SelectTokens("json.appID[*]").Where(t => t.Type == JTokenType.Object || t.Type == JTokenType.Null)
                .SequenceEqual(JToken.Parse(json2).SelectTokens("json.appID[*]").Where(t => t.Type == JTokenType.Object || t.Type == JTokenType.Null)));
        }

        static IEnumerable<string> GetJson()
        {
            var json = new[]
            {
                @"{
  ""total_events"": 3551574,
  ""json.appID"": [
    {
      ""count"": 3551024,
      ""term"": 1
    },
    {
      ""count"": 256,
      ""term"": 2
    },
    []                /* <----- I need to ignore this empty array */
  ],
  ""unique_field_count"": 2
}",
                @"{
  ""total_events"": 3551574,
  ""json.appID"": /* Some Comment */ [
    null,
    ""bad string"",
    101010101,
    {
      ""count"": 3551024,
      ""term"": 1
    },
    {
      ""count"": 256,
      ""term"": 2
    },
    [],                /* <----- I need to ignore this empty array */
    [1,1,,1,1],
  ],
  ""unique_field_count"": 2
}",
            };

            return json;
        }
    }

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: " + Environment.Version);
			Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}

    public class AssertionFailedException : System.Exception
    {
        public AssertionFailedException() : base() { }

        public AssertionFailedException(string s) : base(s) { }
    }

    public static class Assert
    {
        public static void IsTrue(bool value)
        {
            IsTrue(value, "failed");
        }

        public static void IsTrue(bool value, string message)
        {
            if (value == false)
                throw new AssertionFailedException(message ?? "failed");
        }
    }
;