I have some Web API that returns objects and collections, when deserialized I can get a JToken
, which can be either a JObject
or a JArray
. I want to write an extension for the JToken
type that will translate JToken
to JObject
or JArray
.
I know that it is possible to make a parameter to select one of two types or to make two different methods, but I want to make one universal method for conversion.
How am I trying to implement such a task:
namespace App.Extensions
{
public static class JsonExtensions
{
public static T To<T>(this JToken token) => (T)token;
}
}
And getting an error:
Unable to convert type "Newtonsoft.Json.Linq.JToken" in "T".
Maybe there are more civil methods of solution?
i made you example to convert to class
void Main()
{
string json = "{\"employees\":[{\"name\":\"Shyam\",\"email\":\"shyamjaiswal@gmail.com\"},{\"name\":\"Bob\",\"email\":\"bob32@gmail.com\"},{\"name\":\"Jai\",\"email\":\"jai87@gmail.com\"}]}";
var jobj = JsonConvert.DeserializeObject<JToken>(json);
jobj.To<Root>().Dump();
}
public static class JsonExtensions
{
public static T To<T>(this JToken token) where T : class
=> (T)token.ToObject(typeof(T));
}
public class Employee
{
public string name { get; set; }
public string email { get; set; }
}
public class Root
{
public List<Employee> employees { get; set; }
}
if you need to work with Tokens - use JContainer
public static class JsonExtensions
{
public static T To<T>(this JToken token) where T : JContainer
=> (T)token.ToObject(typeof(T));
}
and call would be
jobj.To<JObject>().Dump();