Reputation: 179
I´m writing a function which parses JSON and may return different types of objects. Say, I´m parsing an bird json and want to return a bird object, then a tiger json and want to get a tiger object insted.
How can I do this? Should I use a dynamic object? And, if this is the answer, HOW?
I don´t want to overload the logic on each type of object I´d want to get from it.
Thanks in advance,
Ariel
Upvotes: 1
Views: 96
Reputation: 5538
Are you using JSON.NET? Generics seem to be the right answer, at any rate. Something like this:
public T CreateAnimal<T>(string json) {
return JsonConvert.DeserializeObject<T>(json);
}
Note that in order to use this, you would have to know ahead of time which type of object you would expect in the json, so you can call it like this:
Tiger t = CreateAnimal<Tiger>(tigerJson);
Upvotes: 1
Reputation: 3484
To prevent bloated code, you could instantiate your animal objects convention-based:
Activator.CreateInstance("YourAssemblyNameContainingAnimalTypes", animalString);
Upvotes: 0