questions/47317792/handling-json-response-which-sometimes-doesnt-have-array

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 System.Collections.ObjectModel;

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

// https://stackoverflow.com/questions/47317792/handling-json-response-which-sometimes-doesnt-have-array#47317792

    public class TolerantCollectionConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            if (objectType.IsPrimitive || objectType == typeof(string) || objectType.IsArray)
                return false;
            return objectType.GetCollectionItemTypes().Count() == 1;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return null;
            }
            else if (reader.TokenType == JsonToken.StartArray)
            {
                existingValue = existingValue ?? serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
                serializer.Populate(reader, existingValue);
                return existingValue;
            }
            else
            {
                reader.Skip();
                return existingValue;
            }
        }

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

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

    public static class TypeExtensions
    {
        /// <summary>
        /// Return all interfaces implemented by the incoming type as well as the type itself if it is an interface.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static IEnumerable<Type> GetInterfacesAndSelf(this Type type)
        {
            if (type == null)
                throw new ArgumentNullException();
            if (type.IsInterface)
                return new[] { type }.Concat(type.GetInterfaces());
            else
                return type.GetInterfaces();
        }

        public static IEnumerable<Type> GetCollectionItemTypes(this Type type)
        {
            foreach (Type intType in type.GetInterfacesAndSelf())
            {
                if (intType.IsGenericType
                    && intType.GetGenericTypeDefinition() == typeof(ICollection<>))
                {
                    yield return intType.GetGenericArguments()[0];
                }
            }
        }
    }

    public class Field
    {
        public string FIELD_NAME { get; set; }
        public string VALUE { get; set; }
        public int FIELD_ID { get; set; }

		// Verify the converter works for general collections and not just List<T>.
        public ObservableCollection<Option> OPTIONS { get; set; }
    }

    public class Option
    {
        public string VALUE { get; set; }
        public int DISPLAY_ORDER { get; set; }
        public string DISPLAY { get; set; }
    }

    class TestClass
    {

        public static void Test()
        {
            foreach (var stringTest in GetJson())
            {
                var settings = new JsonSerializerSettings
                {
                    Converters = { new TolerantCollectionConverter() },
                };
                var obj = JsonConvert.DeserializeObject<Field>(stringTest, settings);
                var newJson = JsonConvert.SerializeObject(obj, Formatting.Indented, settings);
                Console.WriteLine("\nDeserialized and re-serialized {0}", obj);
                Console.WriteLine(newJson);
            }

            Console.WriteLine("\nDone.");
        }

        static string[] GetJson()
        {
            var json = new[]
            {
                @"{
    ""FIELD_NAME"": ""Survey"",
    ""VALUE"": """",
    ""FIELD_ID"": 1234,
    ""OPTIONS"":[
        { ""VALUE"": ""GENERAL"", ""DISPLAY_ORDER"": 1, ""DISPLAY"": ""GENERAL"" },
        { ""VALUE"": ""HPEFS"",   ""DISPLAY_ORDER"": 3, ""DISPLAY"": ""HPEFS"" },
        { ""VALUE"": ""NONE"",    ""DISPLAY_ORDER"": 3, ""DISPLAY"": ""NONE"" }]
}",
                @"{
    ""FIELD_NAME"": ""Survey"",
    ""VALUE"": """",
    ""FIELD_ID"": 1234,
    ""OPTIONS"":{}
}"            };

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