HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

Deserialize JSON object into dynamic object using Json.net

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
netobjectdeserializedynamicusingintojson

Problem

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

Solution

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

Code Snippets

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);
1000
 string
 6

Context

Stack Overflow Q#4535840, score: 629

Revisions (0)

No revisions yet.