JsonSubtypes#135

CSharp · Console

/Program.cs

using System;
using JsonSubTypes;
using Newtonsoft.Json;

namespace subTypesIssue
{
    public class Program
    {
        public static void Main()
        {
            var settings = new JsonSerializerSettings();
            settings.Converters.Add(JsonSubtypesConverterBuilder
                .Of<IResult>("Type")
                .RegisterSubtype(typeof(Some<>), "Some")
                .RegisterSubtype(typeof(None), "None")
                .SerializeDiscriminatorProperty()
                .Build());

            var input = new Some<int> {Value = 42};
            var json = JsonConvert.SerializeObject(input, typeof(IResult), settings);

            // Would expect {"Type":"Some","Value":42} but get "Impossible to serialize type" error
            Console.WriteLine(json);

            // Would be nice if deserialization also worked and the generic type could be inferred from the value
            var result = JsonConvert.DeserializeObject<IResult>(json, settings);

            Console.WriteLine(result);
        }
    }

    public interface IResult
    {
    }

    public class Some<T> : IResult
    {
        public T Value { get; set; }
    }

    public class None : IResult
    {
    }
}
;