I just got a hold of JSON.NET
and its been great so far.
However, I cannot figure out how to determine the type
of a serialized object when deserializing it.
How can I determine the object's class to cast it?
To clarify my question, let's say I wanted to do this
string json = <<some json i don't know>>
var data = JsonConvert.DeserializeObject(json);
if (data is Person)
{
//do something
}
else if (data is Order)
{
//do something else
}
Does Json.NET support this kind of functionality?
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.
you can use dynamic
type
JsonConvert.DeserializeObject<dynamic>(JSONtext)
it may help you
IDictionary < string, JToken > Jsondata = JObject.Parse(yourJsonString); foreach(KeyValuePair < string, JToken > element in Jsondata) { string innerKey = element.Key; if (element.Value is JArray) { // Process JArray } else if (element.Value is JObject) { // Process JObject } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With