Newtonsoft JSON - 动态对象 [英] Newtonsoft JSON - Dynamic Objects

查看:26
本文介绍了Newtonsoft JSON - 动态对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Newtonsoft JSON 库对传入的原始 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.

起点是以下 JSON 字符串:

The starting point is the following JSON string:

{
  "task": {
    "dueDate": "2012-12-03T00:00:00"
  }
}

没什么太复杂的...

在代码中我正在这样做:

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' 不包含对任务"

'Newtonsoft.Json.Linq.JObject' does not contain a definition for 'task'

堆栈跟踪:在 CallSite.Target(Closure , CallSite , Object ) 在System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,Tret](CallSite站点,T0 arg0)

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;

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

推荐答案

你可以试试这个:

dynamic task = JObject.Parse(rawJson);

文档:动态查询 JSON

这篇关于Newtonsoft JSON - 动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆