Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize Abstract Class

I have an abstract class 'Server' which I create in my JavaScript in my UI and then I want to have a method on my Web Service which does the following:

public List<Database> GetDatabases(Server server)
{
    Type type = server.GetType();
    Server x = null;

    if (typeof (SqlServer2005Server).Equals(type))
    {
        x = new SqlServer2005Server();
    }

    // Return the Databases from the server
    return x.GetDatabases();
}

The issue I am having is that Server can not be deserialized as it is abstract, Do I need to have a method for each Server I have which inherits from the concrete type i.e

public List<Database> GetDatabases(SqlServer2005Server server)
{
    // Return the Databases from the server
    return SqlServer2005Serverx.GetDatabases();
}

public List<Database> GetDatabases(OracleServer server)
{
    // Return the Databases from the server
    return SqlServer2005Serverx.GetDatabases();
}

I would really appreciate your help as i am not sure what is the best solution

The exact error I receive is:

Instances of abstract classes cannot be created.

like image 872
Phill Duffy Avatar asked Mar 11 '09 10:03

Phill Duffy


People also ask

Can we deserialize an abstract class?

The JSON contains a list of objects which is abstract and it's not possible to deserialize it.

Which one is correct class for JsonSerializer?

The JsonSerializer is a static class in the System. Text. Json namespace. It provides functionality for serializing objects to a JSON string and deserializing from a JSON string to objects.

Is polymorphic Deserialization possible in System text JSON?

There is no polymorphic deserialization (equivalent to Newtonsoft. Json's TypeNameHandling ) support built-in to System.


1 Answers

WCF will support inheritance, but you need to decorate your data contract with the known type attibute. For example:

[DataContract]
[KnownType(typeof(Customer))]
class Contact
{
   [DataMember]
   public string FirstName
   {get;set;}

   [DataMember]
   public string LastName
   {get;set;}
}
[DataContract]
class Customer : Contact
{
   [DataMember]
   public int OrderNumber
   {get;set;}
}

HTH.

like image 68
stephenl Avatar answered Oct 09 '22 13:10

stephenl