TheProgrammer
TheProgrammer

Reputation: 61

How can I call the value from a Jtoken

So I have a JSON object, then I loop through all the Children and add the items to a list of JTokens. When I debug, the list contains the following : https://i.sstatic.net/uXZDI.jpg

When I show a MessageBox I get the following: https://i.sstatic.net/oUuji.jpg

The problem is, I just want the string text as: 'Volunteer'. How can I do it?

List<JToken> objecten = new List<JToken>();

JObject json = JObject.Parse(content);
foreach (JToken token in json.Children<JToken>())
{
   objecten.Add(token);
}

MessageBox.Show(objecten[1].ToString());

If I want to get the role in a string variable, I would like to do it like this but I don't know how it works:

string role = objecten.Role;

Upvotes: 1

Views: 4458

Answers (2)

krost
krost

Reputation: 11

You can try with this:

JObject json = JObject.Parse(content);
foreach (KeyValuePair<string, JToken> sourcePair in json)
           {
               if (sourcePair.Key == "Role")
                    role = sourcePair.Value.ToString();
            }

With recursion you can pass through all json object without know the complete path of the attributes

Upvotes: 1

jtabuloc
jtabuloc

Reputation: 2535

You can use SelectToken wherein you can select your desire value base on their path. See this reference.

JObject json = JObject.Parse(content);    
var value = json.SelectToken("role").Value<string>();      

Add a path to select role. The path will depend on your JSON structure.

Example value of content

{
   response : {
       role : volunteer,
       success: true,
       token: eyJhbGci...
   }
}

JObject json = JObject.Parse(content);    
var value = json.SelectToken("response.role").Value<string>();

Upvotes: 4

Related Questions