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 . can you please suggest what are all the option do i have?
I am using Newtonsoft library for serialization and serialization.
开发者_StackOverflow中文版Thanks in advance
I don't use Newtonsoft library. 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.
find $type
i=find next colon
j=find next comma
grab token between i and 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 ;-)
Its fairly simple using the Newtonsoft library.
JObject json = JObject.Parse(JsonText);
string type = json["$type"].ToString();
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!
精彩评论