【问题标题】:Getting Exception while accessing value of JToken - Cannot access child value on Newtonsoft.Json.Linq.JValue访问 JToken 的值时出现异常 - 无法访问 Newtonsoft.Json.Linq.JValue 上的子值
【发布时间】:2015-05-16 06:21:55
【问题描述】:

我正在开发一个测试用例来模拟我的 C# 方法。我无法使用 token["DocumentID"] 访问 JToken 的 DocumentID 属性。我收到 System.InvalidOperationException -“无法访问 Newtonsoft.Json.Linq.JValue 上的子值”。

string response = "[\r\n  \"{ \\\"DocumentID\\\": \\\"fakeGuid1\\\",\\\"documentNotes\\\": \\\"TestNotes1\\\"}\"\r\n]";
//Response has escape charaters as  this is being returned by a mockMethod which is supposed to return JSon.ToString().

string[] fakeGuidForExecutiveSummary = new string[]{"fakeGuid1"};
string fakeResponseFromExecutiveSummaryProxy = "{ \"DocumentID\": \"fakeGuid1\",\"documentNotes\": \"TestNotes1\"}";

JArray jsonResponse = JArray.Parse(response);
//Value of jsonResponse from Debugger - {[  "{ \"DocumentID\": "fakeGuid1\",\"documentNotes\": \"TestNotes1\"}" ]}

JToken token = jsonResponse[0];
//Value of token from Debugger - { "DocumentID": fakeGuid1","documentNotes": "TestNotes1"}
Assert.AreEqual(fakeGuidForExecutiveSummary[0], token["DocumentID"]);

【问题讨论】:

  • 什么是response?另外,您根本没有使用fakeResponseFromExecutiveSummaryProxy,那么您实际使用的是什么JSON?
  • 还有,fakeGuidForExecutiveSummary是什么?
  • 请尝试创建一个Minimal, Complete, and Verifiable example 的代码来演示您的问题。由于您省略了一些步骤(例如初始化fakeGuidForExecutiveSummary),我们只能猜测问题所在。
  • 我刚刚编辑了我的问题。谢谢。
  • fakeGuidForExecutiveSummary 等于响应。

标签: c# json linq


【解决方案1】:

你没有展示你如何初始化fakeGuidForExecutiveSummary。假设您按照以下方式进行操作:

        string fakeResponseFromExecutiveSummaryProxy = "{ \"DocumentID\": \"fakeGuid1\",\"documentNotes\": \"TestNotes1\"}";
        var fakeResponse = JToken.Parse(fakeResponseFromExecutiveSummaryProxy);
        var fakeGuidForExecutiveSummary = fakeResponse["DocumentID"];

那么问题是fakeGuidForExecutiveSummaryJValue,而不是JTokenJArray。如果您尝试按索引访问(不存在的)子值,您的代码将抛出您看到的异常。

相反,您需要执行以下操作:

        string response = @"[{ ""DocumentID"": ""fakeGuid1"",""documentNotes"": ""TestNotes1""}]";
        JArray jsonResponse = JArray.Parse(response);
        JToken token = jsonResponse[0];

        //Value of token from Debugger - { "DocumentID": fakeGuid1","documentNotes": "TestNotes1"}
        Assert.AreEqual(fakeGuidForExecutiveSummary, token["DocumentID"])

更新

鉴于您更新的代码,问题在于您的示例 JSON response 有太多级别的字符串转义:\\\"DocumentID\\\"。您可能将 Visual Studio 中显示的转义字符串复制到源代码中,然后再次对其进行转义。

改成

        string response = "[\r\n  { \"DocumentID\": \"fakeGuid1\",\"documentNotes\": \"TestNotes1\"}\r\n]";

【讨论】:

  • 我编辑了我的问题以更准确。这与我的问题非常接近,我尝试了您的解决方案,但仍然遇到同样的错误。
  • 在上面的代码中添加一个附加行 JToken token = JToken.Parse(jsonResponse[0].ToString());
猜你喜欢
  • 2021-01-23
  • 2021-08-09
  • 1970-01-01
  • 2019-08-24
  • 2021-08-21
  • 2018-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多