Reputation: 42105
I'm using SignalR to receive a type name and Json, which for now I've relatively naively implemented by concatenating when with a pipe symbol on the server:
var ctx = GlobalHost.ConnectionManager.GetConnectionContext<MyConnection>();
ctx.Connection.Broadcast(message.GetType().FullName + "|" + JsonConvert.SerializeObject(message));
On the client, I'm trying to deserialise back to the correct Type, but of course can't use any of the generic methods on JsonConvert
so I came up with this:
var pipePos = eventMessageString.IndexOf("|", StringComparison.Ordinal);
var typeName = eventMessageString.Substring(0, pipePos);
var eventJson = eventMessageString.Substring(pipePos + 1);
var eventType = Type.GetType(typeName);
var evt = JsonConvert.DeserializeObject(eventJson, eventType);
The only trouble is that evt
is a Newtonsoft.Json.Linq.JObject
, when really it should be an instance of the eventType
type.
Is there a better way to do this, or at least a solution to get this working? I feel like I've missed something glaringly obvious - maybe I've been staring at it for too long?
Many thanks in advance.
Upvotes: 2
Views: 1109
Reputation: 34391
Is the eventType non-null? When calling Type.GetType, you need the assembly-qualified name of the type.
Upvotes: 3