Newtonsoft JSON - 动态对象 [英] Newtonsoft JSON - Dynamic Objects
问题描述
我使用的是Newtonsoft JSON库执行对传入原始JSON动态deserialisation并已发现的东西,我只是无法解释。
的出发点是以下JSON字符串:
{
任务:{
的dueDate:2012-12 -03T00:00:00
}
}
没有什么太复杂了有...
在代码中,我再这样做:
VAR DYN = JsonConvert.DeserializeObject<动态>(rawJson);
日期时间的dueDate = dyn.task.dueDate.Value;
此代码已实行数月,工作得很好,但是在最近的测试版本我们看到以下错误:
Newtonsoft.Json.Linq.JObject'不包含
'任务'<定义/ p>
堆栈跟踪:在CallSite.Target(封闭,调用点,对象)在
System.Dynamic.UpdateDelegates.UpdateAndExecute1 [T0,TRET](调用点
现场,T0为arg0)
块引用>
现在,这是其中获得奇,一切开始后,如果我从上面修改代码重新工作:
日期时间的dueDate = dyn.task.dueDate.Value;
到
日期时间的dueDate = DYN [任务] [的dueDate]值。
所以,虽然这是固定我不明白为什么这个修复它,什么可能的原因可能是。没有任何人有任何想法
解决方案您可以试试这个:
动态任务= JObject.Parse(rawJson);
文件:的 查询JSON动态
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
解决方案You can try this:
dynamic task = JObject.Parse(rawJson);
Documentation: Querying JSON with dynamic
这篇关于Newtonsoft JSON - 动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!