https://stackoverflow.com/questions/18994685/how-to-handle-both-a-single-item-and-an-array-for-the-same-property-using-json-n

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.Diagnostics;
using System.Collections.ObjectModel;

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

using NUnit.Framework; // Throws NUnit.Framework.AssertionException

    //https://stackoverflow.com/questions/18994685/how-to-handle-both-a-single-item-and-an-array-for-the-same-property-using-json-n

    public class SingleOrArrayListConverter : JsonConverter
    {
        // Adapted from this answer https://stackoverflow.com/a/18997172
        // to https://stackoverflow.com/questions/18994685/how-to-handle-both-a-single-item-and-an-array-for-the-same-property-using-json-n
        // by Brian Rogers https://stackoverflow.com/users/10263/brian-rogers
        readonly bool canWrite;
        readonly IContractResolver resolver;

        public SingleOrArrayListConverter() : this(false) { }

        public SingleOrArrayListConverter(bool canWrite) : this(canWrite, null) { }

        public SingleOrArrayListConverter(bool canWrite, IContractResolver resolver)
        {
            this.canWrite = canWrite;
            // Use the global default resolver if none is passed in.
            this.resolver = resolver ?? new JsonSerializer().ContractResolver;
        }

        static bool CanConvert(Type objectType, IContractResolver resolver)
        {
            Type itemType;
            JsonArrayContract contract;
            return CanConvert(objectType, resolver, out itemType, out contract);
        }

        static bool CanConvert(Type objectType, IContractResolver resolver, out Type itemType, out JsonArrayContract contract)
        {
            if ((itemType = objectType.GetListItemType()) == null)
            {
                itemType = null;
                contract = null;
                return false;
            }
            // Ensure that [JsonObject] is not applied to the type.
            if ((contract = resolver.ResolveContract(objectType) as JsonArrayContract) == null)
                return false;
            var itemContract = resolver.ResolveContract(itemType);
            // Not implemented for jagged arrays.
            if (itemContract is JsonArrayContract)
                return false;
            return true;
        }

        public override bool CanConvert(Type objectType) { return CanConvert(objectType, resolver); }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            Type itemType;
            JsonArrayContract contract;

            if (!CanConvert(objectType, serializer.ContractResolver, out itemType, out contract))
                throw new JsonSerializationException(string.Format("Invalid type for {0}: {1}", GetType(), objectType));
            if (reader.MoveToContent().TokenType == JsonToken.Null)
                return null;
            var list = (IList)(existingValue ?? contract.DefaultCreator());
            if (reader.TokenType == JsonToken.StartArray)
                serializer.Populate(reader, list);
            else
                // Here we take advantage of the fact that List<T> implements IList to avoid having to use reflection to call the generic Add<T> method.
                list.Add(serializer.Deserialize(reader, itemType));
            return list;
        }

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

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var list = value as ICollection;
            if (list == null)
                throw new JsonSerializationException(string.Format("Invalid type for {0}: {1}", GetType(), value.GetType()));
            // Here we take advantage of the fact that List<T> implements IList to avoid having to use reflection to call the generic Count method.
            if (list.Count == 1)
            {
                foreach (var item in list)
                {
                    serializer.Serialize(writer, item);
                    break;
                }
            }
            else
            {
                writer.WriteStartArray();
                foreach (var item in list)
                    serializer.Serialize(writer, item);
                writer.WriteEndArray();
            }
        }
    }

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

        internal static Type GetListItemType(this Type type)
        {
            // Quick reject for performance
            if (type.IsPrimitive || type.IsArray || type == typeof(string))
                return null;
            while (type != null)
            {
                if (type.IsGenericType)
                {
                    var genType = type.GetGenericTypeDefinition();
                    if (genType == typeof(List<>))
                        return type.GetGenericArguments()[0];
                }
                type = type.BaseType;
            }
            return null;
        }
    }

    public class SingleOrArrayCollectionConverter<TCollection, TItem> : JsonConverter
        where TCollection : ICollection<TItem>
    {
        // Adapted from this answer https://stackoverflow.com/a/18997172
        // to https://stackoverflow.com/questions/18994685/how-to-handle-both-a-single-item-and-an-array-for-the-same-property-using-json-n
        // by Brian Rogers https://stackoverflow.com/users/10263/brian-rogers
        readonly bool canWrite;

        public SingleOrArrayCollectionConverter() : this(false) { }

        public SingleOrArrayCollectionConverter(bool canWrite) { this.canWrite = canWrite; }

        public override bool CanConvert(Type objectType)
        {
            return typeof(TCollection).IsAssignableFrom(objectType);
        }

        static void ValidateItemContract(IContractResolver resolver)
        {
            var itemContract = resolver.ResolveContract(typeof(TItem));
            if (itemContract is JsonArrayContract)
                throw new JsonSerializationException(string.Format("Item contract type {0} not supported.", itemContract));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            ValidateItemContract(serializer.ContractResolver);
            if (reader.MoveToContent().TokenType == JsonToken.Null)
                return null;
            var list = (ICollection<TItem>)(existingValue ?? serializer.ContractResolver.ResolveContract(objectType).DefaultCreator());
            if (reader.TokenType == JsonToken.StartArray)
                serializer.Populate(reader, list);
            else
                list.Add(serializer.Deserialize<TItem>(reader));
            return list;
        }

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

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            ValidateItemContract(serializer.ContractResolver);
            var list = value as ICollection<TItem>;
            if (list == null)
                throw new JsonSerializationException(string.Format("Invalid type for {0}: {1}", GetType(), value.GetType()));
            if (list.Count == 1)
            {
                foreach (var item in list)
                {
                    serializer.Serialize(writer, item);
                    break;
                }
            }
            else
            {
                writer.WriteStartArray();
                foreach (var item in list)
                    serializer.Serialize(writer, item);
                writer.WriteEndArray();
            }
        }
    }
	
    class TestClass
    {
		public static void Test()
		{
			TestSingleOrArrayListConverter.Test();
			TestSingleOrArrayCollectionConverter.Test();
			
            Console.WriteLine("\nAll tests passed.");
		}
	}

    class TestSingleOrArrayCollectionConverter
    {
        public static void Test()
        {
            TestQuestion();
            TestObservableCollectionNoWriteRoundTrip();
            TestObservableCollectionRoundTrip();
        }

        class Item
        {
            public string Email { get; set; }
            public int Timestamp { get; set; }
            public string Event { get; set; }

            [JsonConverter(typeof(SingleOrArrayCollectionConverter<ObservableCollection<string>, string>))]
            public ObservableCollection<string> Category { get; set; }
        }

        static void TestQuestion()
        {
            var json = @"[
  {
    ""email"": ""[email protected]"",
    ""timestamp"": 1337966815,
    ""category"": [
      ""newuser"",
      ""transactional""
    ],
    ""event"": ""open""
  },
  {
    ""email"": ""[email protected]"",
    ""timestamp"": 1337966815,
    ""category"": ""olduser"",
    ""event"": ""open""
  }
]
";
            var expectedJson = @"[
  {
    ""email"": ""[email protected]"",
    ""timestamp"": 1337966815,
    ""category"": [
      ""newuser"",
      ""transactional""
    ],
    ""event"": ""open""
  },
  {
    ""email"": ""[email protected]"",
    ""timestamp"": 1337966815,
    ""category"": [""olduser""],
    ""event"": ""open""
  }
]
";
            var settings = new JsonSerializerSettings
            {
                // Applied since your JSON is camel cased
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
            };
            var list = JsonConvert.DeserializeObject<List<Item>>(json, settings);
            var json2 = JsonConvert.SerializeObject(list, Formatting.Indented, settings);

            Debug.WriteLine(json2);

            Assert.IsTrue(JToken.DeepEquals(JToken.Parse(expectedJson), JToken.Parse(json2)));

        }

        static void TestObservableCollectionNoWriteRoundTrip()
        {
            var expectedJsonNoWrite = @"[
null,
[],
[""single""],
[""double"", ""double""],
[""triple"", ""triple"", ""triple""]
]";
            var json = @"[
null,
[],
""single"",
[""double"", ""double""],
[""triple"", ""triple"", ""triple""]
]";

            var settings = new JsonSerializerSettings
            {
                Converters = { new SingleOrArrayCollectionConverter<ObservableCollection<string>, string>() },
            };

            var root = JsonConvert.DeserializeObject<List<ObservableCollection<string>>>(json, settings);

            Assert.IsTrue(root.Count == 5 && root[0] == null && root[1].Count == 0 && root[2].Count == 1 && root[3].Count == 2 && root[4].Count == 3);

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

            Assert.IsTrue(JToken.DeepEquals(JToken.Parse(expectedJsonNoWrite), JToken.Parse(json2)));

            Debug.WriteLine(json2);
        }

        static void TestObservableCollectionRoundTrip()
        {
            var json = @"[
null,
[],
""single"",
[""double"", ""double""],
[""triple"", ""triple"", ""triple""]
]";

            var settings = new JsonSerializerSettings
            {
                Converters = { new SingleOrArrayCollectionConverter<ObservableCollection<string>, string>(true) },
            };

            var root = JsonConvert.DeserializeObject<List<ObservableCollection<string>>>(json, settings);

            Assert.IsTrue(root.Count == 5 && root[0] == null && root[1].Count == 0 && root[2].Count == 1 && root[3].Count == 2 && root[4].Count == 3);

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

            Assert.IsTrue(JToken.DeepEquals(JToken.Parse(json), JToken.Parse(json2)));

            Debug.WriteLine(json2);
        }
    }

    class TestSingleOrArrayListConverter
    {
        public static void Test()
        {
            TestQuestion();
            TestNotImplementedCases();
            TestCommentRoundTrip();
            TestWriteRoundTrip();
            TestNoWriteRoundTrip();
            TestListObject();
        }

		class Item
		{
			public string Email { get; set; }
			public int Timestamp { get; set; }
			public string Event { get; set; }

			public List<string> Category { get; set; }
		}

        static void TestQuestion()
        {
            var json = @"[
  {
    ""email"": ""[email protected]"",
    ""timestamp"": 1337966815,
    ""category"": [
      ""newuser"",
      ""transactional""
    ],
    ""event"": ""open""
  },
  {
    ""email"": ""[email protected]"",
    ""timestamp"": 1337966815,
    ""category"": ""olduser"",
    ""event"": ""open""
  }
]
";
            var settings = new JsonSerializerSettings
            {
                // Pass true if you want single-item lists to be reserialized as single items
                Converters = { new SingleOrArrayListConverter(true) },

                // Applied since your JSON is camel cased
                ContractResolver = new CamelCasePropertyNamesContractResolver(), 
            };
            var list = JsonConvert.DeserializeObject<List<Item>>(json, settings);
            var json2 = JsonConvert.SerializeObject(list, Formatting.Indented, settings);

            Debug.WriteLine(json2);

            Assert.IsTrue(JToken.DeepEquals(JToken.Parse(json), JToken.Parse(json2)));

        }

        static void TestNotImplementedCases()
        {
            var converter = new SingleOrArrayListConverter();

            Assert.IsTrue(converter.CanConvert(typeof(ListObject<string>)) == false);
            Assert.IsTrue(converter.CanConvert(typeof(string)) == false);
            Assert.IsTrue(converter.CanConvert(typeof(List<int[]>)) == false);
            Assert.IsTrue(converter.CanConvert(typeof(List<ObservableCollection<List<string>>>)) == false);
            Assert.IsTrue(converter.CanConvert(typeof(JToken)) == false);
            Assert.IsTrue(converter.CanConvert(typeof(object)) == false);
        }

        static void TestListObject()
        {
            var collection = new ListObject<string> { "one" };
            var settings = new JsonSerializerSettings
            {
                // Pass true to the constructor if single-item lists should be reserialized as values rather than arrays.
                Converters = { new SingleOrArrayListConverter(true) },
            };
            var token1 = JToken.FromObject(collection, JsonSerializer.Create(settings));
            var token2 = JToken.FromObject(collection, JsonSerializer.Create(null));

            Assert.IsTrue(JToken.DeepEquals(token1, token2));

            var json = token2.ToString();

            var collection2 = JsonConvert.DeserializeAnonymousType(json, collection, settings);

            Assert.IsTrue(collection.SequenceEqual(collection2));

            Debug.WriteLine(token1);
        }

        static void TestWriteRoundTrip()
        {
            var json = @"[
null,
[],
""single"",
[""double"", ""double""],
[""triple"", ""triple"", ""triple""]
]";

            var settings = new JsonSerializerSettings
            {
                Converters = { new SingleOrArrayListConverter(true) },
            };

            var root = JsonConvert.DeserializeObject<List<List<string>>>(json, settings);

            Assert.IsTrue(root.Count == 5 && root[0] == null && root[1].Count == 0 && root[2].Count == 1 && root[3].Count == 2 && root[4].Count == 3);

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

            Assert.IsTrue(JToken.DeepEquals(JToken.Parse(json), JToken.Parse(json2)));

            Debug.WriteLine(json2);
        }

        static void TestNoWriteRoundTrip()
        {
            var expectedJsonNoWrite = @"[
null,
[],
[""single""],
[""double"", ""double""],
[""triple"", ""triple"", ""triple""]
]";
            var json = @"[
null,
[],
""single"",
[""double"", ""double""],
[""triple"", ""triple"", ""triple""]
]";

            var settings = new JsonSerializerSettings
            {
                Converters = { new SingleOrArrayListConverter() },
            };

            var root = JsonConvert.DeserializeObject<List<List<string>>>(json, settings);

            Assert.IsTrue(root.Count == 5 && root[0] == null && root[1].Count == 0 && root[2].Count == 1 && root[3].Count == 2 && root[4].Count == 3);

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

            Assert.IsTrue(JToken.DeepEquals(JToken.Parse(expectedJsonNoWrite), JToken.Parse(json2)));

            Debug.WriteLine(json2);
        }

        static void TestCommentRoundTrip()
        {
            var expectedJsonNoWrite = @"[
null,
[],
[""single""],
[""double"", ""double""],
[""triple"", ""triple"", ""triple""]
]";
            var json = @"[
/* Comment */null,
/* Comment */[],
/* Comment */""single"",
/* Comment */[""double"", ""double""],
/* Comment */[""triple"", ""triple"", ""triple""]
]";

            var settings = new JsonSerializerSettings
            {
                Converters = { new SingleOrArrayListConverter() },
            };

            var root = JsonConvert.DeserializeObject<List<List<string>>>(json, settings);

            Assert.IsTrue(root.Count == 5 && root[0] == null && root[1].Count == 0 && root[2].Count == 1 && root[3].Count == 2 && root[4].Count == 3);

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

            Assert.IsTrue(JToken.DeepEquals(JToken.Parse(expectedJsonNoWrite), JToken.Parse(json2)));

            Debug.WriteLine(json2);
        }
    }

    [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
    class ListObject<T> : List<T>
    {
        [JsonProperty("Count")]
        int MyCount { get { return Count; } }

        [JsonProperty("Items")]
        T[] Items
        {
            get
            {
                return ToArray();
            }
            set
            {
                Clear();
                if (value != null)
                    AddRange(value);
            }
        }
    }
	
	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;
			}
		}
	}
;