2

I may be approaching this incorrectly but I have an HTTP endpoint that is going to be receiving a JSON payload with an anonymous object of data and a name parameter that defines what type it should be cast to. The trouble is I'm not quite sure how to deserialize it dynamically to accept that type. Here is what I have tried so far.

// Get request body
RequestBodyObject body = await req.Content.ReadAsAsync<RequestBodyObject>();

var assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
Type typeObject = Type.GetType($"MyNamespace, {assemblyName}");

// Cast data obtained
var specificObject = JsonConvert.DeserializeObject<typeObject>(body.Data.ToString());

My problem of course is that I cannot use typeObject in between the <> part of my Json convert line. If I specify a static object in that place my code works fine but I'm looking for a dynamic solution since any type of object from a certain set could be passed in just fine.

Any ideas?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
tokyo0709
  • 1,897
  • 4
  • 28
  • 49

1 Answers1

1

You could try;

var specificObject = JsonConvert.DeserializeObject(body.Data.ToString(),typeObject);

Also, you don't get any type with;

Type typeObject = Type.GetType($"MyNamespace, {assemblyName}");

You should specify type name and it would look like;

var typeObject = System.Reflection.Assembly.GetExecutingAssembly().GetType("JsonObject");
lucky
  • 12,734
  • 4
  • 24
  • 46
  • Thank you this solved my first issue with the dynamic runtime cast. I ran into another issue with the cast however on this issue, https://stackoverflow.com/questions/48271723/dynamic-casting-json-doesnt-create-the-same-object-as-an-explicit-cast – tokyo0709 Jan 15 '18 at 22:44