saule icon indicating copy to clipboard operation
saule copied to clipboard

Abstract / Derived Class Deserialization

Open aariabov opened this issue 7 years ago • 3 comments

Hello. I have model binding problem, like this. Can I make such binding with json api and saule?

aariabov avatar Sep 22 '18 12:09 aariabov

It doesn't really seem to fit very nicely in the JSON api spec to do such a thing. Especially since the $type value must be the first value in the object. Perhaps it could work if you create an attribute named $type?

public class MyResource : ApiResource
{
  public MyResource()
  {
    Attribute("$type");
  }
}

then in your payload:

{
  "data": {
    "type": "my-type",
    "attributes": {
      "$type": "MyApp.Api.ConcreteType"
    }
  }
}

I suppose the "recommended" way to do it using JSON API is to set different types for the different subclasses under the data hash.

joukevandermaas avatar Sep 23 '18 14:09 joukevandermaas

I came here to ask something very similliar. Right now iirc the "type" parameter sent by the client is not interpreted at all in the deserialization. It would be great if we had a way to do this. ALSO it would be great to be allowed to return multiple APIResources that are derived from each other from a webapi action.

~Cheers

PhyberApex avatar Oct 04 '18 14:10 PhyberApex

Just came back to tell @aariabov that he probably can make use of the Default settings for the used Newtonsoft serializer. I just added these lines:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.Auto,
};

and was able to use derived classed in nested attributes. To use derived classes in top level (ApiResources) would probably require a lot of work on Saule and should be really thought about as it seems to go against the RESTful philosphy and actually would be better suited for RPC.

~Cheers

PhyberApex avatar Oct 05 '18 08:10 PhyberApex