访问JToken值时获取异常 - 无法访问Newtonsoft.Json.Linq.JValue上的子值

时间:2015-03-13 16:53:44

标签: c# json linq

我正在研究一个测试用例来模拟我的C#方法。我无法使用令牌[" 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"]);

1 个答案:

答案 0 :(得分: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]";