开发者

How can I customize the deserialization of JSON in ASP.NET MVC?

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 concret开发者_StackOverflowe 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
      });


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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜