Convert JObject to type at runtime

user156888 picture user156888 · Jul 30, 2014 · Viewed 11.5k times · Source

I am writing a simple event dispatcher where my events come in as objects with the clr type name and the json object representing the original event (after the byte[] has been processed into the jobject) that was fired. I'm using GetEventStore if anyone wants to know the specifics.

I want to take that clr type to do 2 things:

  1. find the classes that implements IHandles and
  2. call Consume(clr type) on that class

I have managed to get part 1 working fine with the following code:

     var processedEvent = ProcessRawEvent(@event);
     var t = Type.GetType(processedEvent.EventClrTypeName);

     var type = typeof(IHandlesEvent<>).MakeGenericType(t);

     var allHandlers = container.ResolveAll(type);


     foreach (var allHandler in allHandlers)
     {
         var method = allHandler.GetType().GetMethod("Consume", new[] { t });
         method.Invoke(allHandler, new[] { processedEvent.Data });
     }

ATM the issue is that processedEvent.Data is a JObject - I know the type of processedEvent.Data because I have t defined above it.

How can I parse that JObject into type t without doing any nasty switching on the type name?

Answer

Amir Popovich picture Amir Popovich · Jul 30, 2014

Use ToObject:

var data = processedEvent.Data.ToObject(t);

or if you have a known type then:

MyObject data = processedEvent.Data.ToObject<MyObject>();