c# - 访问 JToken 的值时出现异常 - 无法访问 Newtonsoft.Json.Linq.JValue 上的子值

标签 c# json linq

我正在研究一个测试用例来模拟我的 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"]);

最佳答案

您没有展示如何初始化 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]";

关于c# - 访问 JToken 的值时出现异常 - 无法访问 Newtonsoft.Json.Linq.JValue 上的子值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29037825/

相关文章:

c# - EF Core 2.0 一对一 - 这是什么情况?

java - 如何使用 Selenium WebDriver 和 Java 在文本区域中输入 JSON?

php - Instagram API - 仅检索视频

json - Pandas 数据框到JSON列表格式

c# - Linq 到实体 : adding a where condition to a child relationship

c# - 如何加入 2 个列表,其中一个列表包含 2 个元素?

c# - 如何在 Gmail 的主题行中发送图片?

c# - 带有本地 SQL Server CE DLL 的 Entity Framework 代码优先 "ADO.NET provider not found"

c# - 无法迭代 iTextSharp 中的字段

c# - 将 LINQ 表达式从 C# 转换为 VB.NET 在 Group by 中引发异常