0

OK.

I have a set of data in the form of JSON. Each object represents one of a number of sub-classes from a single base class and one of the fields in the JSON object holds the name of sub-class

EDIT: I've obviously phrased the question badly; let me try again

Assume I'm making a number of calls to a spell that, with each call returns a JSON object. Each object looks a bit like this ...

{
    "type":"FooA",
    "FieldA":"AA",
    "FieldB":"AB"
}

Now, whilst each object looks to have the same structure as the others, they actually represent very different classes. The appropriate type is stored in the 'type' field.

I can pass the JSON to a method that does something like this...

public Foo MakeFoos(string json)
{
    var super = JsonConvert.Deserialize<Foo>(json);
    switch(super.Type)
    {
        case "FooA":
            return JsonConvert.Deserialize<FooA>(json);

        case "FooB":
            return JsonConvert.Deserialize<FooB>(json);

        case "FooC":
            return JsonConvert.Deserialize<FooC>(json);

        case "FooD":
            return JsonConvert.Deserialize<FooD>(json);
    }
}

What I would like to know is if there is a way of creating and instance of the correct type for each entry without having to deserialize the object twice.

Stuart Hemming
  • 1,553
  • 2
  • 21
  • 44
  • You could user reflection to get all inherited types of the base class and then use the constructor of the class that's name is equal to type – Alex Krupka Jul 14 '16 at 15:44
  • 1
    Can you please clarify if you are having problem with getting correct types in array during deserialization (which your JSON hints at) or just optimizing "string to type" conversion (as shown in your sample code)? – Alexei Levenkov Jul 14 '16 at 15:51
  • @AlexeiLevenkov, the latter. – Stuart Hemming Jul 14 '16 at 15:52
  • I think this would be good duplicate - [Getting a System.Type from type's partial name](http://stackoverflow.com/questions/179102/getting-a-system-type-from-types-partial-name) which has complete sample of what @AlexKrupka suggested. (Not voting to close yet as most of this question in current state does not match what is actually asked) – Alexei Levenkov Jul 14 '16 at 15:57
  • @StuartHemming so for one json file(that has multiple objects with multiple types), what do you expect the output to be List ? where the items are each created by a separate constructor for the relevant type ? If so, your code doesn't do that. – Zein Makki Jul 14 '16 at 16:10
  • 1
    Use a `JsonConverter`. See [How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?](https://stackoverflow.com/questions/8030538) and [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/questions/19307752). – dbc Jul 14 '16 at 18:12

0 Answers0