vendredi 12 août 2016

JsonConvert.DeserializeObject in C# when only the string name of the desired object is known

Let's say information about a document is stored in a barcode, and the structure of the information varies according to the type of document. But the type of the document is not known beforehand; the barcode tells us what kind of document we are dealing with:

The barcode value won't store delimited strings like this:

author|date|subject
author|date|subject|approvedby1;approvedby2

but will contain json notation:

 FOO|{"author": "Smokey", "date": "01/01/2015", "subject": "widgets"}

 GOO|{"author": "Smokey", "date": "01/01/2015", "subject": "widgets", "approvals": ["Mike","Jane"]}

When we fetch the barcode text data, we see from the value to the left of the | delimiter that we need to instantiate either a FOO or a GOO. We grab the string to the right of the | and feed it to JsonConvert.

How to tell JsonConvert.DeserializeObject<some type> to return a GOO object from its json representation?

  var myGoo = JsonConvert.DeserializeObject<?>(jsonStringGOO)

What goes between the angle brackets < >?

EDIT: Ideally, without resorting to a switch statement.

Let's assume that the current namespace contains class definitions for all of the possible types.





Aucun commentaire:

Enregistrer un commentaire