1

I have an issue with deserializing a class that has method within it that should be triggered once the object is deserialized. For the purpose of this question i will simplify the problem as much as possible.

public class Cat:IAnimal
{
 public string CatBreed{get;set;}
 public void Sounds()
 { 
   console.log("Meow")
 }
}

public class Dog:IAnimal
{
 public string DogBreed{get;set;}
 public void Sounds()
 { 
   console.log("Woof");
 }
}
public interface IAnimal
{
  void Sounds();
}

So somewhere along the lines both classes are being instantiated and serialized and being forwarded to for deserialization in a same place, where it's not important which class it is we only need to trigger Sounds method. So this didn't work because instance of the interface cannot be created

JsonConvert.DeserializeObject<IAnimal>(json)

But since i know that the arriving objects will surely have method Sounds() i tried converting it into dynamic or plain Object which led to discovery that JsonConvert is converting the objects and dynamics into JObjects, and the method Sounds cannot be invoked because JObject has no definition for it. If you provide specific class to the DeserializeObject, the method will exists and work as intended but for the purpose of being completely generic i need to invoke it in this or similar manner.

Is there a way of achieving this?

user1033698
  • 89
  • 1
  • 7
  • Have you tried to ask for the concreted class instead of the interface ? JsonConvert.DeserializeObject(json) – vdefeo Sep 11 '17 at 16:05
  • Yes, but that won't do, since in real problem there are 50 or so different classes that have same method that needs to be invoked, so going with a concrete class won't work. – user1033698 Sep 11 '17 at 16:07
  • https://stackoverflow.com/a/29689910/1536425 I think this implementation could help you – vdefeo Sep 11 '17 at 16:10
  • That would help out if i had control over serialization process, it's a communication between web api's so the objects are being automatically serialized. – user1033698 Sep 11 '17 at 16:15
  • Do you have access to the web api settings? – Brian Rogers Sep 11 '17 at 18:30
  • Not currently, but generally i do. – user1033698 Sep 11 '17 at 18:31
  • 1
    Since your `Cat` and `Dog` objects have different sets of properties, you create a custom converter like the ones in [How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?](https://stackoverflow.com/q/8030538) and [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752). To automate choosing the concrete class using reflection see [JsonConverter with Interface](https://stackoverflow.com/a/33322680). – dbc Sep 12 '17 at 17:11

0 Answers0