简体   繁体   English

如何从 JSON 文本中获取反序列化的 C# 对象的类型?

[英]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.

相关问题 C#从反序列化的json对象中获取值 - C# get value from deserialized json object C#从反序列化JSON对象中的数组获取值 - C# get value from Array in Deserialized JSON Object 如何从反序列化JSON对象获取值? - How to get values from Deserialized JSON object? 反序列化JSON以包含对C#中另一个反序列化对象的引用 - Deserialize JSON to type containing reference to another deserialized object in C# 使用反射从动态反序列化 Json 对象获取属性 - .NET Core 3.1 C# - Get Properties From Dynamic Deserialized Json Object with Reflection - .NET Core 3.1 C# 从C#中的Object(反序列化json)中检索数据 - Retrieving data from an Object(deserialized json) in C# 如何使用 Newton 和 System.Text.Json 一样使用默认构造函数参数获取反序列化的 C# 记录? - How to get deserialized C# record with default constructor parameter with Newton as with System.Text.Json? 如何在c#中访问反序列化的Json对象的各个元素? - How to access the individual elements of a deserialized Json object in c#? C# 如何将嵌套的 JSON 的一部分保存到 object 属性中,但不反序列化? - C# How to save part of nested JSON into object property, but not deserialized? 如何使用 ZD7EFA19FBE7D32372FD5ADB607 中的 WPF 从 TCPClient 读取序列化和反序列化的 json object? - How to read serialized and deserialized json object from TCPClient using WPF in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM