Search code examples
c#jsonjson.net

How to extract a field from JSON


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?


Solution

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

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