Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic variable not working in C# with Json.Net

Tags:

c#

json.net

Can anyone tell me why I get an error when trying to output"dJson2.Type" in the code below?

    string Json1= @"[{'Id':1, 'FirstName':'John', 'LastName':'Smith'}, {'Id':2, 'FirstName':'Jane', 'LastName':'Doe'}]";
    dynamic dJson1= JsonConvert.DeserializeObject(Json1);
    Console.WriteLine(dJson1.GetType());
    Console.WriteLine(dJson1.Type);

    string Json2 = @"{'Id':1, 'FirstName':'John', 'LastName':'Smith'}";
    dynamic dJson2 = JsonConvert.DeserializeObject(Json2);
    Console.WriteLine(dJson2.GetType());
    Console.WriteLine(dJson2.Type);

The program dies on the Console.WriteLine(dJson2.Type) statement. The output of the program is...

Newtonsoft.Json.Linq.JArray
Array
Newtonsoft.Json.Linq.JObject
(should say Object here, I think)

Inspecting the local variables, dJson2 has a "Type" property with value "Object".

like image 657
Boulder Keith Avatar asked May 14 '26 04:05

Boulder Keith


1 Answers

This is because JObject behaves similarly as System.Dynamic.ExpandoObject. Try to change your example to:

  string Json2 = @"{'Id':1, 'FirstName':'John', 'LastName':'Smith'}";
  dynamic dJson2 = JsonConvert.DeserializeObject(Json2);
  dJson2.Type = "mynewfield";
  Console.WriteLine(dJson2.GetType());
  Console.WriteLine(dJson2.Type);

If you want to get property of underlying type you need to cast it (to JToken or JObject), otherwise requested property will be searched in IDictionary<string, JToken> that JObject implements.

This example may help:

  dynamic oobj = new JObject();
  oobj.Type = "TEST";
  Console.WriteLine(oobj.Type);
  Console.WriteLine(((JObject)oobj).Type);
like image 67
DolphinSX Avatar answered May 16 '26 17:05

DolphinSX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!