Dhinnesh Jeevan
Dhinnesh Jeevan

Reputation: 549

Convert JSON to an object, then performing different actions based on object type

Previously, I have an OrderedDictionary where I convert it into JSON, then at some parts of the code I need to deserialize it back to OrderedDictionary.

Now, I need to change the type of that property to a List. I need to do a backward compatibility. How can I code such that when deserializing the JSON, I deserialize it to an object, then I check if object is List, do something, else if object is OrderedDictionary, do something.

Currently if I deserialize it to an object, I get a JObject. I'm using Newtonsoft.Json.

What I'm expecting to have is something like:

var x = JsonConvert.DeserializeAnonymousType(jsonString, new object());

if (x is List)
 doSomething1();
else if (x is OrderedDictionary)
 doSomething2();

Upvotes: 3

Views: 174

Answers (3)

Mango Wong
Mango Wong

Reputation: 649

Use below:

object x = JsonConvert.DeserializeObject(jsonString);

if (x is Newtonsoft.Json.Linq.JObject) // OrderedDictionary
    doSomething1();
else if (x is Newtonsoft.Json.Linq.JArray) // List
    doSomething2();

This works only with Json.NET and jsonString must be string serialized also by Json.NET.

From Json.NET's Serialization Guide, List (implemented IList) would be serialized in JSON array, and OrderedDictionary (implemented IDictionary) would be serialized as JSON object. Therefore, the returned value would be of different type, which are of JArray and JObject respectively.

Upvotes: 2

Cheng Chen
Cheng Chen

Reputation: 43523

The JSON library won't (can't) help you decide the best target type, you need to tell it. What do you think is the "correct" target type if you don't provide one?

//JSON:   { Name = "sweety", Age = 1 }

class Kid
{
    public string Name { get; set; }
    public int Age { get; set }
}

class Cat
{
    public string Name { get; set; }
    public int Age { get; set }
}

In another word, a JSON string has no information of the type it comes from. So you need to tell the library to de-serialize the JSON string to a specific type (even an anonymous type).

I think you shouldn't serialize the OrderedDictionary<K,V>(or the List<T>) itself, but the items inside them, and add one more property indicating the type like this:

class MyClass
{
    public string Flag { get; set; }
    public MyData[] DataObjects { get; set; }
}

Put the items of your dictionary/list into a MyClass instance and serialize it (with different Flag property values). And you will always get an instance of MyClass after de-serialization, check the Flag property to decide which section of code should be run.

Upvotes: 1

Bassam Alugili
Bassam Alugili

Reputation: 17023

use the type like that:

var x = JsonConvert.DeserializeAnonymousType(json,new OrderedDictionary());
System.Console.WriteLine(x.GetType());

Output:
System.Collections.Specialized.OrderedDictionary

Upvotes: 2

Related Questions