【问题标题】:JObject to dynamic not working in Newtonsoft.Json 9.0JObject 到动态在 Newtonsoft.Json 9.0 中不起作用
【发布时间】:2017-02-15 14:14:52
【问题描述】:

这里有很多答案建议使用以下方法将JObject 用作dynamic

dynamic dynObj = JObject.Parse(jsonString);

dynamic dynObj = JsonConvert.DeserializeObject<dynamic>(jsonString);

我的jsonString 很简单:{"id":"123","name":"abc"}

它似乎在 Newtonsoft.Json 9.0 中不起作用。当我尝试其中任何一个时,我仍然得到一个类型为 object {Newtonsoft.Json.Linq.JObject} 的对象。

当我尝试通过dynObj.id 访问属性时,我得到一个异常error CS1061: 'object' does not contain a definition for 'id' and no extension method 'id' accepting a first argument of type 'object' could be found

【问题讨论】:

  • 显示你的jsonString
  • 刚刚添加了jsonString
  • 你有MCVE - 我刚试过,它似乎按预期工作(v9.0.1)?
  • 我想我会尝试在我的项目之外创建一个示例。
  • 无法复制,见dotnetfiddle.net/aXmSUv

标签: c# json json.net


【解决方案1】:

当 DLR 第一次尝试绑定到对象的属性时,您可能会看到调试器中第一次抛出异常。可以安全地忽略此异常,如果您继续运行代码,它应该可以正常工作。

见:Lots of first chance Microsoft.CSharp.RuntimeBinderExceptions thrown when dealing with dynamics

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2021-07-29
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    相关资源
    最近更新 更多