Convert JObject to runtime input

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

I want to take this type of clr to do 2 things:

  • find classes that implement ihandles and
  • calling Consume (type clr) in this class

I managed to get part 1 working perfectly 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 problem is that the processed Event.Data is a JObject - I know the type of processed Event.Data, because I have t defined above.

How can I parse this JObject into type t without any unpleasant switching of type name?

+7
casting c # get-event-store
source share
3 answers

Use ToObject :

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

or if you have a known type, then:

 MyObject data = processedEvent.Data.ToObject<MyObject>(); 
+7
source share

It turned out to be very simple:

 method.Invoke(allHandler, new[] { JsonConvert.DeserializeObject(processedEvent.Data.ToString(), t) }); 
0
source share

If for some reason you are stuck in the older Newtonsoft Json.NET package ( pre 4.5.11 circa 2012) and do not have access to the already mentioned JToken.ToObject(Type) , you can reuse what it does inside :

 var someJObject = ...; // wherever it came from; actually a JToken var type = typeof(MyExpectedType); MyExpectedType myObject; using (var jsonReader = new JTokenReader(someJObject)) myObject = serializer.Deserialize(jsonReader, type); 

I mention this only because I was working on a project that could not just upgrade the Nuget package for Json.NET to the latest version. In addition, this has nothing to do with the version of the .NET Framework.

0
source share

All Articles