Grasshopper
Grasshopper

Reputation: 1808

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.

Thanks in advance

Upvotes: 0

Views: 5294

Answers (3)

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!

Upvotes: 0

Grasshopper
Grasshopper

Reputation: 1808

Its fairly simple using the Newtonsoft library.

JObject json = JObject.Parse(JsonText);
string type = json["$type"].ToString();

Upvotes: 0

sgtz
sgtz

Reputation: 9009

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 ;-)

Upvotes: 1

Related Questions