[英]How to get the type of deserialized C# object from JSON text?
I am trying to get the type of serialized C# object in JSON Text ( $type in JSON text) without deserialising the JSON text to object again .我试图在 JSON 文本(JSON 文本中的 $type)中获取序列化 C# 对象的类型,而无需再次将 JSON 文本反序列化为对象。 can you please suggest what are all the option do i have?你能建议我有哪些选择吗?
I am using Newtonsoft library for serialization and serialization.我正在使用 Newtonsoft 库进行序列化和序列化。
Thanks in advance提前致谢
I don't use Newtonsoft library.我不使用 Newtonsoft 库。 However, assuming that $type is either at the start of the file or at the end I'd probably use string functions (psudocode below) which'd be quite fast.但是,假设 $type 位于文件的开头或结尾,我可能会使用字符串函数(下面的伪代码),这会非常快。
find $type查找 $type
i=find next colon i=找到下一个冒号
j=find next comma j=查找下一个逗号
grab token between i and j在 i 和 j 之间抓取令牌
trim that token修剪那个令牌
do something useful with the token.用令牌做一些有用的事情。 Make a type out of it with reflection?用反射制作一个类型?
How does that sound?听起来怎么样? While you are at it you could write an extension method.当您使用它时,您可以编写一个扩展方法。 Hit +1 several times and I'll think about writing the code ;-)多次点击 +1,我会考虑编写代码 ;-)
try this试试这个
var jsonObj = JObject.Parse("your json string");
var props = jsonObj.Properties();
foreach (var prop in props)
{
Console.WriteLine(prop.Value.Type);
}
I hope this help you!我希望这对你有帮助!
Its fairly simple using the Newtonsoft library.使用 Newtonsoft 库相当简单。
JObject json = JObject.Parse(JsonText);
string type = json["$type"].ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.