JavaEar 专注于收集分享传播有价值的技术资料

Getting Exception while accessing value of JToken - Cannot access child value on Newtonsoft.Json.Linq.JValue

I am working on a test case to emulate my C# method. I am unable to access the DocumentID property of the JToken using token["DocumentID"]. I am getting System.InvalidOperationException - "Cannot access child value on 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个回答

    最佳答案
  1. You don't show how you initialize fakeGuidForExecutiveSummary. Assuming you do it in the following way:

            string fakeResponseFromExecutiveSummaryProxy = "{ \"DocumentID\": \"fakeGuid1\",\"documentNotes\": \"TestNotes1\"}";
            var fakeResponse = JToken.Parse(fakeResponseFromExecutiveSummaryProxy);
            var fakeGuidForExecutiveSummary = fakeResponse["DocumentID"];
    

    Then the problem is that fakeGuidForExecutiveSummary is a JValue, not a JToken or JArray. Your code will throw the exception you see if you try to access a (nonexistent) child value by index.

    Instead you need to do the following:

            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"])
    

    Update

    Given your updated code, the problem is that your sample JSON response has too many levels of string escaping: \\\"DocumentID\\\". You probably copied escaped strings shown in Visual Studio into the source code, then escaped them some again.

    Change it to

            string response = "[\r\n  { \"DocumentID\": \"fakeGuid1\",\"documentNotes\": \"TestNotes1\"}\r\n]";