2015-03-13 60 views
1

我正在測試用例來模擬我的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"]); 
+0

什麼是'response'?另外,你根本沒有使用'fakeResponseFromExecutiveSummaryProxy',所以你實際使用的是什麼JSON? – dbc 2015-03-13 17:16:10

+0

另外,什麼是'fakeGuidForExecutiveSummary'? – dbc 2015-03-13 17:23:13

+0

請嘗試創建一個[最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve)代碼來演示您的問題。既然你省略了一些步驟(比如初始化'fakeGuidForExecutiveSummary'),我們只能猜測問題是什麼。 – dbc 2015-03-13 17:36:17

回答

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]"; 
+0

我編輯我的問題更準確。這是非常接近我的問題,我試過你的解決方案,但仍然有相同的錯誤。 – 2015-03-13 18:16:29

+0

@SantoshK - 答案已更新。 – dbc 2015-03-13 18:31:14

+0

在上面的代碼中添加additinal行012xxJToken token = JToken.Parse(jsonResponse [0] .ToString()); – 2015-03-13 18:33:08