我正在研究一个测试用例来模拟我的 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"];
那么问题是 fakeGuidForExecutiveSummary
是 JValue
, 不是 JToken
或 JArray
.如果您尝试通过索引访问(不存在的)子值,您的代码将抛出异常。
相反,您需要执行以下操作:
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/