1

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

4
  • 3
    I think you want to look at Generics (C# Programming Guide) Commented Apr 8, 2014 at 4:15
  • Do you know the type of object you expect to be returned when you call the method? Commented Apr 8, 2014 at 4:16
  • @astander Yep! I'd definitely use Generics too. Probably a single Parse<T> method. Commented Apr 8, 2014 at 4:17
  • Yes I know, jmcilhinney Commented Apr 8, 2014 at 12:24

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you dvlsg, I´ll give it a try and let you know
Should I use T.GetType() from within CreateAnimal function to discover the type of T ?
Possibly. May I ask what you are using to parse your JSON, or are you attempting to write the parsing code yourself? If you are using JSON.NET (which I highly recommend), then the call to JsonConvert.DeserializeObject will take all of the matching properties from the JSON string and place them on the object for you -- in this case, a Tiger object.
0

To prevent bloated code, you could instantiate your animal objects convention-based:

Activator.CreateInstance("YourAssemblyNameContainingAnimalTypes", animalString);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.