Deserialize JSON object into dynamic object using Json.net

C#.Netjson.net

C# Problem Overview


Is it possible to return a dynamic object from a json deserialization using json.net? I would like to do something like this:

dynamic jsonResponse = JsonConvert.Deserialize(json);
Console.WriteLine(jsonResponse.message);

C# Solutions


Solution 1 - C#

Json.NET allows us to do this:

dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");

Console.WriteLine(d.number);
Console.WriteLine(d.str);
Console.WriteLine(d.array.Count);

Output:

 1000
 string
 6

Documentation here: LINQ to JSON with Json.NET

See also JObject.Parse and JArray.Parse

Solution 2 - C#

As of Json.NET 4.0 Release 1, there is native dynamic support:

[Test]
public void DynamicDeserialization()
{
	dynamic jsonResponse = JsonConvert.DeserializeObject("{\"message\":\"Hi\"}");
	jsonResponse.Works = true;
	Console.WriteLine(jsonResponse.message); // Hi
	Console.WriteLine(jsonResponse.Works); // True
	Console.WriteLine(JsonConvert.SerializeObject(jsonResponse)); // {"message":"Hi","Works":true}
	Assert.That(jsonResponse, Is.InstanceOf<dynamic>());
	Assert.That(jsonResponse, Is.TypeOf<JObject>());
}

And, of course, the best way to get the current version is via NuGet.

Updated (11/12/2014) to address comments:

This works perfectly fine. If you inspect the type in the debugger you will see that the value is, in fact, dynamic. The underlying type is a JObject. If you want to control the type (like specifying ExpandoObject, then do so.

enter image description here

Solution 3 - C#

If you just deserialize to dynamic you will get a JObject back. You can get what you want by using an ExpandoObject.

var converter = new ExpandoObjectConverter();    
dynamic message = JsonConvert.DeserializeObject<ExpandoObject>(jsonString, converter);

Solution 4 - C#

I know this is old post but JsonConvert actually has a different method so it would be

var product = new { Name = "", Price = 0 };
var jsonResponse = JsonConvert.DeserializeAnonymousType(json, product);

Solution 5 - C#

Yes you can do it using the JsonConvert.DeserializeObject. To do that, just simple do:

dynamic jsonResponse = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonResponse["message"]);

Solution 6 - C#

Note: At the time I answered this question in 2010, there was no way to deserialize without some sort of type, this allowed you to deserialize without having go define the actual class and allowed an anonymous class to be used to do the deserialization.


You need to have some sort of type to deserialize to. You could do something along the lines of:

var product = new { Name = "", Price = 0 };
dynamic jsonResponse = JsonConvert.Deserialize(json, product.GetType());

My answer is based on a solution for .NET 4.0's build in JSON serializer. Link to deserialize to anonymous types is here:

http://blogs.msdn.com/b/alexghi/archive/2008/12/22/using-anonymous-types-to-deserialize-json-data.aspx

Solution 7 - C#

If you use JSON.NET with old version which didn't JObject.

This is another simple way to make a dynamic object from JSON: https://github.com/chsword/jdynamic

NuGet Install

PM> Install-Package JDynamic

Support using string index to access member like:

dynamic json = new JDynamic("{a:{a:1}}");
Assert.AreEqual(1, json["a"]["a"]);

Test Case

And you can use this util as following :

Get the value directly

dynamic json = new JDynamic("1");

//json.Value

2.Get the member in the json object

dynamic json = new JDynamic("{a:'abc'}");
//json.a is a string "abc"

dynamic json = new JDynamic("{a:3.1416}");
//json.a is 3.1416m

dynamic json = new JDynamic("{a:1}");
//json.a is integer: 1

3.IEnumerable

dynamic json = new JDynamic("[1,2,3]");
/json.Length/json.Count is 3
//And you can use json[0]/ json[2] to get the elements

dynamic json = new JDynamic("{a:[1,2,3]}");
//json.a.Length /json.a.Count is 3.
//And you can use  json.a[0]/ json.a[2] to get the elements

dynamic json = new JDynamic("[{b:1},{c:1}]");
//json.Length/json.Count is 2.
//And you can use the  json[0].b/json[1].c to get the num.

Other

dynamic json = new JDynamic("{a:{a:1} }");

//json.a.a is 1.

Solution 8 - C#

Yes it is possible. I have been doing that all the while.

dynamic Obj = JsonConvert.DeserializeObject(<your json string>);

It is a bit trickier for non native type. Suppose inside your Obj, there is a ClassA, and ClassB objects. They are all converted to JObject. What you need to do is:

ClassA ObjA = Obj.ObjA.ToObject<ClassA>();
ClassB ObjB = Obj.ObjB.ToObject<ClassB>();

Solution 9 - C#

If someone is trying to deserialize JSON to an anonymous object, you can do it using NewtonSoft.Json's DeserializeAnonymousType method.

The below example can even deserialize JSON to a list of anonymous objects.

var json = System.IO.File.ReadAllText(@"C:\TestJSONFiles\yourJSONFile.json");
var fooDefinition = new { a = "", b = 0 }; // type with fields of string, int
var fooListDefinition = Enumerable.Range(0, 0).Select(e => fooDefinition).ToList();

var foos = JsonConvert.DeserializeAnonymousType(json, fooListDefinition);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionryudiceView Question on Stackoverflow
Solution 1 - C#Michael PakhantsovView Answer on Stackoverflow
Solution 2 - C#David PedenView Answer on Stackoverflow
Solution 3 - C#Joshua PetersonView Answer on Stackoverflow
Solution 4 - C#epitkaView Answer on Stackoverflow
Solution 5 - C#otealView Answer on Stackoverflow
Solution 6 - C#PhillView Answer on Stackoverflow
Solution 7 - C#chswordView Answer on Stackoverflow
Solution 8 - C#s kView Answer on Stackoverflow
Solution 9 - C#Ash KView Answer on Stackoverflow