Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi have a scenario where i'm getting back json from an API that is using JsonAPI. the json returned can be of two formats as shown below. (simplified for this example)


{  
      "attributes":{ 
    	"AnimalType":"Lion",	  
    	 "Name":"lio",
    	 "Eats":"Meat"
      }
    }



and

{  
       "attributes":{ 
    	"AnimalType":"Chicken",
    	 "Name":"Henry",
    	 "HasFeathers":true
      }
    }


The class that represent the different Json looks like this



<pre lang="c#">public abstract class Animal
        {
            public virtual string AnimalType{ get; set; }
        }
    	
    	
    public class Lion : Animal
        {
            public override string AnimalType{ get; set; }
    		public string Eats { get; set; }
            public string Name{ get; set; }
        }
    
    public class Chicken : Animal
        {
            public override string AnimalType{ get; set; }
    		public bool HasFeathers { get; set; }
            public string Name{ get; set; }
        }


Ho do i go about Deserialize each json to is correct Object without using switch or if statements ?

What I have tried:

Tried googling around for different solutions for this specific issue but had no luck
Posted
Updated 9-Jan-19 14:38pm

1 solution

I wrote an article to help with all different types of questions related to JSON deserialization. You can find the answer to your question in this article: Working with JSON in C# & VB[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900