Moltivie
Moltivie

Reputation: 51

System.InvalidOperationException: Cannot access child value on Newtonsoft.Json.Linq.JValue

I'm trying to bug this out but I can't find any solution.

This is the C# code.

string unraw_json = reader.ReadToEnd();

            var objects = JArray.Parse(unraw_json);

            foreach (JObject items in objects)
                foreach (KeyValuePair<String, JToken> app in items)
                {
                    var appName = app.Key;
                    var username = (String)app.Value["username"];
                    var password = (String)app.Value["password"];

When debugging var appName = "username" while when I reach var username (line 9), it throws me that error.

I've already tried to include the json inside brace brackets but it throws me an error on the var appName. I've also tried to use different parsing and different libraries but I wanted to used the Newtonsoft.Json.Linq library. Can anyone help me out? Thanks.

This is the JSON file:

[
  {
    "username": "root",
    "password": "toor"
  }
]

Upvotes: 1

Views: 2114

Answers (1)

Jeff
Jeff

Reputation: 7674

Your inner foreach iterates over each KeyValuePair in items. app is a KeyValuePair<String, JToken> where the key is "username" and the value is a JToken string containing "root". You're doing your ["username"] and ["password"] indexing one layer too deep.

Since you already know which keys you want, you don't need to iterate over items at all. Just index items directly:

    foreach (JObject items in objects)
    {
        var username = (String)items["username"];
        var password = (String)items["password"];
    }

Upvotes: 2

Related Questions