1

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
      });
1
  • Could you add a code fragment where you send data to the action MyAction? Commented Jul 9, 2010 at 9:17

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.