0

According to NewtonSoft's documentation, this code:

string props = "{\"lot\":\"TEST\",\"mhd\":\"2016-06-17\"}";
dynamic json = JsonConvert.DeserializeObject(props);
string s = json.mhd;

should work, but I get a RunTimeBinderException when I try it. I have Micrsoft.CSharp referenced and the compile works (it is a runtime error). I am compiling against .NET 4.0, using NewtonSoft version 7.

I tried accessing as json["mhd"], which works fine.

Am I missing something?

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • Exception is raised at the deserialisation or at the access of mhd ? And the json is not of the same shape as in the sample. "[" "]" is missing and the date format could be not deserializable. – Guillaume Beauvois Jun 17 '16 at 13:04
  • 3
    In the latest version of NewtonSoft.Json it deserializes without a problem. – GeralexGR Jun 17 '16 at 13:04
  • @GuillaumeBeauvois it throws on `string s = json.mhd`. – Bart Friederichs Jun 17 '16 at 13:06
  • 1
    The json object is a `Newtonsoft.Json.Linq.JObject` – Candide Jun 17 '16 at 13:08
  • using your code I recreated a console app and it worked. I did however find this post that might potentially be the solution. http://stackoverflow.com/questions/20487305/runtimebinderexception-while-using-newtonsoft-json-with-dynamic-after-installing/33429521#33429521 – Bearcat9425 Jun 17 '16 at 13:10

3 Answers3

2

The json object is a JObject, so to get the value you need do:

string s = (string)json["mhd"];
Candide
  • 30,469
  • 8
  • 53
  • 60
1

I try this case in Newtonsoft.Json 3.5.8 version ,I get this error. When I upgrade Newtonsoft.Json package version to 4.5.1 it works . I think it has bug on older version.

Umut Catal
  • 421
  • 4
  • 11
0

@Candide pointed out what was wrong with your example, but if you still want to use json.mhd syntax and have real dynamic object to work with you can do it.

Try to deserialize it using the ExpandoObjectConverter:

var converter = new ExpandoObjectConverter();
dynamic json = JsonConvert.DeserializeObject<ExpandoObject>(props, converter);
klappvisor
  • 1,099
  • 1
  • 10
  • 28