Boulder Keith
Boulder Keith

Reputation: 675

Dynamic variable not working in C# with 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".

Upvotes: 3

Views: 1436

Answers (1)

DolphinSX
DolphinSX

Reputation: 91

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

Upvotes: 1

Related Questions