Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft JSON - Dynamic Objects

I am using the Newtonsoft JSON library to perform dynamic deserialisation on incoming raw JSON and have found something that I just can't explain.

The starting point is the following JSON string:

{   "task": {     "dueDate": "2012-12-03T00:00:00"   } } 

Nothing too complex there...

In code I am then doing this:

var dyn = JsonConvert.DeserializeObject<dynamic>(rawJson); DateTime dueDate = dyn.task.dueDate.Value; 

This code has been in place for months and works fine, however in a recent test build we were seeing the following error:

'Newtonsoft.Json.Linq.JObject' does not contain a definition for 'task'

Stack Trace: at CallSite.Target(Closure , CallSite , Object ) at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)

Now this is where is gets odd, everything starts to work again if I change the code above from:

DateTime dueDate = dyn.task.dueDate.Value; 

to

DateTime dueDate = dyn["task"]["dueDate"].Value; 

So, although this is "fixed" I don't understand why this fixes it and what the possible cause could be. Does anybody have any ideas

like image 649
MrEyes Avatar asked Dec 03 '12 12:12

MrEyes


People also ask

Can JSON be dynamic?

A dynamic JSON file will be created to store the array of JSON objects. Consider, we have a database named gfg, a table named userdata. Now, here is the PHP code to fetch data from database and store them into JSON file named gfgfuserdetails. json by converting them into an array of JSON objects.

How do I create a JSON object dynamically in node JS?

To create JSON object dynamically via JavaScript, we can create the object we want. Then we call JSON. stringify to convert the object into a JSON string. let sitePersonnel = {}; let employees = []; sitePersonnel.

How do I make a JSON object with multiple arrays in C#?

Json json = new Json(); json. result = new object[] { new {name = "John", address = "US"}, new {name = "Josh", address = "Japan"} }; // json. error = ... and so on string output = JsonConvert. SerializeObject(product);


1 Answers

You can try this:

dynamic task = JObject.Parse(rawJson); 

Documentation: Querying JSON with dynamic

like image 166
Hylaean Avatar answered Sep 18 '22 15:09

Hylaean