CSharp · Console
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 ) );
JsonSerializer serializer = new JsonSerializer();
serializer.TypeNameHandling = TypeNameHandling.Objects;
serializer.Formatting = Formatting.Indented;
string folder = "archivoPrueba.dat";
using (StreamWriter sw = new StreamWriter( @folder ))
using (JsonWriter writer = new JsonTextWriter( sw ))
{
serializer.Serialize( writer, ListaEntes );
}
ListaEntes.Clear();
Console.WriteLine(File.ReadAllText(folder));
using (StreamReader sr = new StreamReader( @folder ))
using (JsonReader reader = new JsonTextReader( sr ))
{
JsonEnteConverter jsonEnteConverter = new JsonEnteConverter();
ListaEntes = ( List< Ente > ) jsonEnteConverter.ReadJson( reader, null, null, serializer );
}
}
}
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 )
{
string type = jObject.Property( "tipo" ).ToString(); //get property Type from your json
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;
}
}
}