Replies: 3 comments
-
Hi, neither the System.Text.Json nor Newtonsoft.Json support that out of the box afaik. It shouldn't be too hard to create a custom "Animal" json converter for either library which selects the correct output type depending on the I'm also not so sure if this can be properly "generalized" in .NET, but I'll happily accept a PR for it if someone pulls it of 😉 |
Beta Was this translation helpful? Give feedback.
-
I had a similar challenge like this where the GraphQL service was returning a union type and I wanted to deserialize into my own custom types. I created both of those types, which had a common interface. These types did have the __typename property on them so I could create a custom converter something like this:
Just have to replace the interface name and concrete class names with whatever fits your use case. Then here is what I did, basically get back the GraphQL object, which I serialize back into JSON, then deserialize that JSON into my RealReponseType class using that converter:
Sorry if that is kinda janky, but it worked real good for my union type. I am not including other code here like checking for Errors in the rawResponse but hopefully you get the idea. Also in my case one of my types was recursive, in that it contained a collection of the union type as well. |
Beta Was this translation helpful? Give feedback.
-
Thank you @akiaz. For that to work, I had to manually replace the __typename by what Newtonsoft expects ($type): That way you don't need to maintain each concrete type in the converter. I would have preferred a solution using System.Text.Json though. |
Beta Was this translation helpful? Give feedback.
-
I have a complex json from GraphQL call, and it contains property
__typename
in different levels to specify what classes should be used to deserialize.By default, System.Text.json deserialize does not support
__typename
and it tries to deserialize into the abstract class instead of the inherited classes (e.g. it tries to deserialize into abstractAnimal
instead ofDog
,Cat
,Horse
, etc.).Please note that different
__typename
show in the structure not just in root.What deserializer/converter should I use that will take into consideration the
__typename
s to properly identify what classes should be used?I don't think I need to implement anything custom because
__typename
is GraphQL standard to indicate type to be used.Beta Was this translation helpful? Give feedback.
All reactions