Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing an unknown type in JSON.NET

Tags:

c#

json.net

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?

like image 915
Maeh Avatar asked Jan 20 '14 23:01

Maeh


People also ask

How do I deserialize JSON?

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.

What is deserialize and serialize in JSON?

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

How does JsonConvert DeserializeObject work?

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.


2 Answers

you can use dynamic type

JsonConvert.DeserializeObject<dynamic>(JSONtext)
like image 135
Omidam81 Avatar answered Oct 04 '22 22:10

Omidam81


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
            }
   }

like image 44
Dibu Avatar answered Oct 04 '22 22:10

Dibu