questions/49109312/c-sharp-newtonsoft-json-deserializeobject-issue

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/49109312/c-sharp-newtonsoft-json-deserializeobject-issue
    public class Root
    {
        [JsonConverter(typeof(TolerantObjectCollectionConverter<FreeGifts>))]
        public List<FreeGifts> FreeGifts { get; set; }
    }

    public class FreeGifts
    {
        [JsonConverter(typeof(SingleOrArrayConverter<FreeGift>))]
        public List<FreeGift> FreeGift { get; set; }
    }

    public class FreeGift
    {
        public string SKU { get; set; }
    }

    class SingleOrArrayConverter<T> : JsonConverter
    {
        // Taken from the answer to 
        // https://stackoverflow.com/questions/18994685/how-to-handle-both-a-single-item-and-an-array-for-the-same-property-using-json-n
        // https://stackoverflow.com/a/18997172
        // by Brian Rogers
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(List<T>));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var tokenType = reader.SkipComments().TokenType;
            if (tokenType == JsonToken.Null)
                return null;
            var list = existingValue as List<T> ?? new List<T>();
            if (tokenType == JsonToken.StartArray)
            {
                serializer.Populate(reader, list);
            }
            else
            {
                list.Add(serializer.Deserialize<T>(reader));
            }
            return list;
        }

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

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

    public class TolerantObjectCollectionConverter<TItem> : JsonConverter
    {
        // Taken from the answer to 
        // https://stackoverflow.com/questions/49030516/how-can-i-ignore-a-blank-array-inside-an-array-of-json-objects-while-deserializi
        // https://stackoverflow.com/a/49078620/

        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;
        }
    }

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

        static void Test(string json)
        {
            var root = JsonConvert.DeserializeObject<Root>(json);

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

            var count1 = JToken.Parse(json).SelectTokens("..SKU").Count();
            var count2 = (root.FreeGifts ?? Enumerable.Empty<FreeGifts>()).SelectMany(f => f.FreeGift ?? Enumerable.Empty<FreeGift>()).Count();
            Assert.IsTrue(count1 == count2);

			Console.WriteLine("\nRe-serialized JSON:");
            Console.WriteLine(json2);
        }

        static IEnumerable<string> GetJson()
        {
            var json = new[]
            {
                @"    {
        ""FreeGifts"": [{
            ""FreeGift"": [{
                    ""SKU"": ""BOWS-SMALL-ALFIE""
                },
                {
                    ""SKU"": ""BOWS-LARGE-ALONZO""
                },
                {
                    ""SKU"": ""BOWS-LARGE-CLANCY""
                },
                {
                    ""SKU"": ""BOWS-SMALL-ALVIN""
                },
                {
                    ""SKU"": ""BOWS-SMALL-CLARK""
                }
            ]
        }]
    }",
            @"    {
        ""FreeGifts"": [{
            ""FreeGift"": {
                ""SKU"": ""BOWS-SMALL-ALVIN""
            }
        }]
    }",
            @"    {
        ""FreeGifts"": [
            """"
        ]
    }",
            };
            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");
        }
    }
;