Error serialize Json abstract class

4

I'm trying to send a list of abstract objects to% of signalr

Server structure (where all values are generated);

public abstract class Comida : Objeto
{
    public int valorNutricional;
    public abstract void Comido(Cola jugador);
}

The object class sets the x and y and This class has 2 children that are;

class ComidaNormal : Comida
{

    public ComidaNormal(int x, int y)
    {
        this.x = x;
        this.y = y;
        this.ancho = 20;
        valorNutricional = 1;
    }
}

class ComidaEnvenenada : Comida
{

    public ComidaEnvenenada(int x, int y)
    {
        this.x = x;
        this.y = y;
        this.ancho = 20;
    }
}

According to the execution flow they will be instantiated;

public static List<Comida> comidas = new List<Comida>();
comidas.Add(new ComidaEnvenenada(x, y));
comidas.Add(new ComidaNormal(x, y));

Everything works perfectly until you have to send that list of comidas to the client;

Server method;

    public List<Comida> getComida()
    {
        return comidas;
    }

Client method;

comidas = await ApiConexion._hub.Invoke<List<Comida>>("getComida");

skipping the next error in this last line of code.

Error;

  

Newtonsoft.Json.JsonSerializationException: 'Could not create an instance of type Snake.Food. Type is an interface or abstract class and can not be instantiated. '

    
asked by Hector Lopez 24.08.2018 в 10:54
source

1 answer

3

The solution to this problem is to configure the deserializador so that use the information in the json . It is not what is used by default.

Serialization is done this way:

Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
serializer.Converters.Add(new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter());
serializer.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
serializer.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto;
serializer.Formatting = Newtonsoft.Json.Formatting.Indented;

using (StreamWriter sw = new StreamWriter(fileName))
using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
{
    serializer.Serialize(writer, obj, typeof(MyDocumentType));
}

When deserializing, the parameters for TypeNameHandling must be set:

MyDocumentType  obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MyDocumentType>(File.ReadAllText(fileName), new Newtonsoft.Json.JsonSerializerSettings 
{ 
    TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto,
    NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
});
  

Original response extracted from Stack Overflow

    
answered by 24.08.2018 / 19:21
source