英文:
How to make an extension for JToken (Newtonsoft) in C#?
问题
我有一些返回对象和集合的Web API,当反序列化时,我可以获得一个JToken
,它可以是JObject
或JArray
。我想为JToken
类型编写一个扩展,将JToken
转换为JObject
或JArray
。
我知道可以通过制作一个参数来选择两种类型之一,或者制作两种不同的方法,但我想制作一个通用的转换方法。
我试图如何实现这样的任务:
namespace App.Extensions
{
public static class JsonExtensions
{
public static T To<T>(this JToken token) => (T)token;
}
}
但是遇到了错误:
无法将类型"Newtonsoft.Json.Linq.JToken"转换为"T"。
也许还有更文明的解决方法?
英文:
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?
答案1
得分: 1
我给你做了一个转换成类的示例
```C#
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; }
}
如果你需要处理 Tokens - 使用 JContainer
public static class JsonExtensions
{
public static T To<T>(this JToken token) where T : JContainer
=> (T)token.ToObject(typeof(T));
}
调用方式如下
jobj.To<JObject>().Dump();
英文:
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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论