Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

c# - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try this:

dynamic task = JObject.Parse(rawJson);

Documentation: Querying JSON with dynamic


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...