[Fork] https://stackoverflow.com/questions/62265721/problem-crash-with-newtonsoft-json-deserializing

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.Reflection;

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/62265721/problem-crash-with-newtonsoft-json-deserializing

    class TestClass
    {
        public static void Test()
        {
			var ListaEntes = new List< Ente >();
			
            ListaEntes.Add( new Enemy( 10 ) );
            ListaEntes.Add( new Enemy( 20 ) );

			var writeSettings = new JsonSerializerSettings
			{
				TypeNameHandling = TypeNameHandling.Objects,
				Formatting = Formatting.Indented,
			};			

            string folder = "archivoPrueba.dat";
            using (var sw = new StreamWriter( @folder ))  // FIXED dispose of writers properly
            using (var writer = new JsonTextWriter( sw ))
			{
 	           JsonSerializer.Create(writeSettings).Serialize( writer, ListaEntes );
			}
            ListaEntes.Clear();
			
			Console.WriteLine(File.ReadAllText(folder));

			var readSettings = new JsonSerializerSettings
			{
				TypeNameHandling = TypeNameHandling.Objects,
				Converters = { new JsonEnteConverter() }, // FIXED
			};
            using (var sr = new StreamReader( @folder )) // FIXED dispose of readers properly
			using (var reader = new JsonTextReader( sr ))
			{
				ListaEntes = JsonSerializer.Create(readSettings).Deserialize<List<Ente>>(reader);
			}

			ListaEntes.Dump();
			
			var json2 = JsonConvert.SerializeObject(ListaEntes, writeSettings);
			
			Assert.AreEqual(File.ReadAllText(folder), json2);
		}	
	}

    public class        Ente
    {
        public string tipo;
        public Animator animator;
    }

    public class        Enemy : Ente
    {
        public          Enemy()
        {
            animator = new Animator( this );
        }

        public          Enemy( int pVar )
        {
            tipo = "enemigo";
        }
    }

    public class        Animator
    {
        Ente father;

        public          Animator( Enemy pEnemy )
        {
            father = pEnemy;
        }
    }

    public class        JsonEnteConverter : Newtonsoft.Json.Converters.CustomCreationConverter< Ente >
    {
        public override Ente Create( Type objectType )
        {
            throw new NotImplementedException();
        }

        public          Ente Create( JObject jObject )
        {
            var type = (string)jObject["tipo"]; // FIXED
            switch ( type )
            {
                case "enemigo":
                    return new Enemy();
            }
            throw new ApplicationException(String.Format("Type not found", type));
        }

        public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer )
        {
            JObject jObject = JObject.Load( reader );
            var targetObject = Create( jObject );
            serializer.Populate( jObject.CreateReader(), targetObject );
            return targetObject;
        }
    }

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