I'm trying to turn an array of bytes into a C# object. I only the know the type of the object at runtime.
Right now, I'm using the JsonConvert.DeserializeObject<T>
to do this, but the result is clunky, mostly because I don't know T
at compile time.
If I knew T
at compile time, I could simply do:
string json = System.Text.Encoding.UTF8.GetString(buffer);
return JsonConvert.DeserializeObject<MyType>(json);
But since I don't, I must do:
string json = System.Text.Encoding.UTF8.GetString(buffer);
var deserializeInfoMethodInfo = typeof(JsonConvert).GetMethods().Where(method => method.Name == "DeserializeObject" && method.IsGenericMethod).First();
return deserializeInfoMethodInfo.MakeGenericMethod(paramInfo.ParameterType).Invoke(null, new object[] { json });
Is there a way to make this simpler?
I have experimented with something like this:
using (MemoryStream stream = new MemoryStream(buffer, bufferIndex, paramLengths[i])) {
using (JsonTextReader jsonReader = new JsonTextReader(new StreamReader(stream))) {
var serializer = new JsonSerializer();
return serializer.Deserialize(jsonReader, paramInfo.ParameterType);
}
}
This is arguably more readable, but I don't like how I have to get the buffer (which I got from calling stream.Read(buffer, 0, length)
in another place), turn it back into a stream, and then have the serializer iterate through the stream again.
Is there a way to trim down the second snippet, or should I stop whining and use the third?