Newtonsoft JSON - 动态对象

0

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

问题描述

限时送ChatGPT账号..

我正在使用 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 - 动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14