I'm trying to wrap my head around how types and generic methods work with Newtonsoft.Json
.
I have the following example base class:
public class Foo
{
public Type Expected;
public object Result;
public Foo()
{
Expected = typeof(RootObject);
}
public void Process()
{
string json = @"{
'Foo': 'oof',
'Baz': 0,
'Bar': [
'Yeet',
'Skeet'
]
}";
Result = JsonConvert.DeserializeObject<Expected>(json); // -> doesnt work
}
}
I'm planning on calling the Process()
method from a derived class after I might've changed the Expected
class type.
However, as this question points out I found after a little research, passing a variable Type to a generic method isn't that easy. After looking into it a little more, I updated the affected line to this:
Result = ((Func<string, object>)JsonConvert.DeserializeObject).Method.MakeGenericMethod(Expected).Invoke(null, new object[]{json});
It works! •ᴗ•
But the resulting variable still is a plain object
, which is quite difficult to handle. I've been trying to cast the result to the Expected
type, but it just won't let me.
Result = (Expected)((Func<string, object>)JsonConvert.DeserializeObject).Method.MakeGenericMethod(Expected).Invoke(null, new object[]{json});
tells me that the type or namespace Expected
couldn't be found. As a more naive approach, I tried to declare my Result
property like so
public Expected Result;
but my dreams didn't come true.
I'm not sure how I should further approach this to get the Result
object to be of type Expected
so I can access its properties easily, or if there is a better way to go about this variable-type-generic-method problem as a whole.
I have the full (sample) markup on dotnetfiddle, thank you for taking your time!