views:

38

answers:

2

I have a controller action that is receiving a complex object via JSON. The object has a property on it that is declared as an abstract type. Currently, the action method never gets executed because when the JSON object is deserialized it chokes on the abstract type.

How can I customize the deserialization phase so that I can supply the correct concrete types to the deserializer?

public class ComplexType
{
    public AbstractClass AbstractObject { get; set; }
}    

public abstract class AbstractClass
{    
}

public class ConcreteClass1 : AbstractClass
{    
}

public class ConcreteClass2 : AbstractClass
{    
}

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult MyAction(ComplexType complexObject)
{

    // code ...

    return Json(myResult);        
}

Called with:

   $.ajax({ 
      url: myUrl, 
      data: JSON.stringify(instanceOfComplexType), 
      cache: false,
      contentType: "application/json",
      complete: function (data, textStatus) {
        // handle response
      },
      dataType: "json",
      type: "POST",
      processData: false
      });
A: 

An Recieving class has allways to have concrete implementations. otherwise, the deserializer cannot instantiate the objects. and there is no other out there that solves you that. you have 2 possibilities.

either remove the abstract from the base class,

or make a implementation of the complexType that implements a concrete AbstractObject property (maybe through contravariance or generics)

cRichter
A: 

In the end I wrote an ActionFilter that processes the incoming JSON using JSON.NET and a custom Converter. The custom Converter is smart enough to decide using the JSON data which of my derived classes it should instantiate.

GiddyUpHorsey