Home > Software engineering >  How to extract a field from JSON
How to extract a field from JSON

Time:08-04

Using NewtonSoft, I am able to parse JSON into this:

var jtoken = JObject.Parse(stringStuff);
Console.WriteLine(jtoken.ToString());     

gives this:

{
  "data": {
    "user": {
      "email": "[email protected]",
      "external-id": "af36-e9fddecdb755"
    },
    "session-token": "G_uJNNxmLNtxcmM2ilB6P_dN67p9XXk3-yn8peUBi7k3xH50Ch7MUQ C"
  },
  "context": "/sessions"
}

However, if I try to get the field "session-token" like this,

var token = jtoken.Value<string>("session-token");

token is null. Not sure what I am doing wrong?

CodePudding user response:

a "session-token" property is nested inside of a "data" property

string token = (string) jtoken["data"]["session-token"]; // G_uJNNxmLNtxcmM2ilB6P_dN67p9XXk3-yn8peUBi7k3xH50Ch7MUQ C

CodePudding user response:

You need to run through the descendants of your root object, and find the JProperty with the name you want -

 var token = root.Descendants()
                 .OfType<JProperty>()
                 .Where(x => x.Name == "session-token")
                 .FirstOrDefault()
                 ?.Value
                 ?.Value<string>();

if(token != null)
{
     //token is "G_uJNNxmLNtxcmM2ilB6P_dN67p9XXk3-yn8peUBi7k3xH50Ch7MUQ C"
}

It's a little awkward, the first .Value returns the JProperty's JToken, then the second .Value gets the string value.

  • Related