访问JToken值时获取异常 - 无法访问Newtonsoft.Json.Linq.J上的子值
我正在测试用例来模拟我的C#方法。我无法使用令牌[“DocumentID”]访问JToken的DocumentID属性。我得到System.InvalidOperationException - “无法访问Newtonsoft.Json.Linq.JValue上的子值”。访问JToken值时获取异常 - 无法访问Newtonsoft.Json.Linq.J上的子值
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]";
我编辑我的问题更准确。这是非常接近我的问题,我试过你的解决方案,但仍然有相同的错误。 – 2015-03-13 18:16:29
@SantoshK - 答案已更新。 – dbc 2015-03-13 18:31:14
在上面的代码中添加additinal行012xxJToken token = JToken.Parse(jsonResponse [0] .ToString()); – 2015-03-13 18:33:08
什么是'response'?另外,你根本没有使用'fakeResponseFromExecutiveSummaryProxy',所以你实际使用的是什么JSON? – dbc 2015-03-13 17:16:10
另外,什么是'fakeGuidForExecutiveSummary'? – dbc 2015-03-13 17:23:13
请尝试创建一个[最小,完整和可验证的示例](http://*.com/help/mcve)代码来演示您的问题。既然你省略了一些步骤(比如初始化'fakeGuidForExecutiveSummary'),我们只能猜测问题是什么。 – dbc 2015-03-13 17:36:17