0

I have a (sql) table with these entries:

Table:

Type (varchar)     Json (varchar)
MyClassA           { "Id": 1, "Name": "OneName" }   
MyClassB           { "Id": 2, "Name": "TwoName" }

I need to call a method in ClassA and/or ClassB to change the Name property.

Something like the next code:

public void Test(string type, string json)
{
   Type type = Type.GetType($"MyNamespace.a.b.{type}, MyDll");

   // Some code here....
   // - Casting to IData    ??
   // - var obj = JsonConvert.DeserializeObject(json);       ??
   // - var obj = JsonConectt.DeserializeObject<type>(json)  ??
   // - var x = Convert.Change(...) ??


   instance.DoSomething("bazinga");

}


public interface IData 
{
   void DoSomething();
}

public class MyClassA : IData
{
   public int Id {get; set;}
   public string Name {get; set;}

   public void DoSomething(string newName)
   {
       Name = newName;
   }
}

public class MyClassB : IData
{
   public int Id {get; set;}
   public string Name {get; set;}

   public void DoSomething(string newName)
   {
       name = $"{Id}, {newName}";
   }
}

Attempt A:

var obj = JsonConvert.DeserializeObject(json);
var ins = obj as IData;
// ins = null

Attempt B:

dynamic obj = JsonConvert.DeserializeObject<dynamic>(json);
// failed

Attempt C:

var obj = JsonConvert.DeseriallizeObject<type>(json);
// Not allowed to use 'type' in this way.
1
  • var obj = JsonConvert.DeseriallizeObject<IData>(json) maybe ? Commented Feb 7, 2018 at 11:44

1 Answer 1

2

You can do the following:

var instance = JsonConvert.DeserializeObject(json, type) as IData;

See HERE for the official documentation. The second parameter will define the type to be deserialized.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.