Turning a byte array into a C# object whose type is unknown at compile time 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&lt;T&gt; 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&lt;MyType&gt;(json);


But since I don't, I must do:

string json = System.Text.Encoding.UTF8.GetString(buffer);
var deserializeInfoMethodInfo = typeof(JsonConvert).GetMethods().Where(method =&gt; method.Name == "DeserializeObject" &amp;&amp; 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?
I think, it can be simplified just a little bit:

static object Deserialize(byte[] buffer, Type type)
{
  using (StreamReader sr = new StreamReader(new MemoryStream(buffer)))
  {
    return JsonConvert.DeserializeObject(sr.ReadToEnd(), type);
  }
}


NB: StreamReader releases/disposes MemoryStream, so you don't have to encapsulate that in a using()



Or You could even do:

static object Deserialize(byte[] buffer, Type type)
{
  return JsonConvert.DeserializeObject(System.Text.Encoding.UTF8.GetString(buffer), type);
}


or:

static object Deserialize(byte[] buffer, Type type)
{
  return JToken.Parse(Encoding.UTF8.GetString(buffer)).ToObject(type);
}