Tim Tim - 3 months ago 21
JSON Question

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.

Answer

How about trying to get the type of the assembly using reflection

var data = input.Split('|');

var assembly = Assembly.LoadFrom("MyDll.dll");

var myType = assembly.GetType("My.Namespace." + data[0]); // GOO / BAR / etc

JsonConvert.DeserializeObject(data[1], myType)

Assembly.GetType(string name)

JsonConvert.DeserializeObject(string value, Type type)

N.B. for debugging, you can get the full name of the type using code like this

var t = typeof(Goo);
Debug.WriteLine(t.FullName);
Comments