Read value from nested Json object


I am trying to read a value from a nested Json object, but I am getting a Parse error:

My Json object:

    "MessageId": "f6774927-37cf-4608-b985-14a7d86a38f9",
    "Time": "2017-04-06T16:28:38.0719933+02:00",
            "value": "0008044834"
            "value": 0
            "value": 0
          var myJsonString = File.ReadAllText(_currentDictory.FullName + @"\test\" + completeFilename);

            var myJObject = JObject.Parse(myJsonString);

            var serial = myJObject.SelectToken("Data.ID").Value<String>();

  Message=Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken.

Reading other values such as "MessageID" works withou any problems, but as soon as I try to get "Data.XYZ" I am getting the error above.

asked on Stack Overflow Jul 19, 2020 by hyperdanny

2 Answers


You need to add value to your json path:

var serial = myJObject.SelectToken("Data.ID.value").Value<String>();

Your current path selects JObject containing one property named value and you can't convert it directly to string.

answered on Stack Overflow Jul 19, 2020 by Guru Stron • edited Jul 19, 2020 by Guru Stron

MessageId is a string. So you can directly read its value. Data on the other hand contains objects (see the { and } ). Therefor you need to use

var serial = myJObject.SelectToken("Data.ID.value").Value<String>();

Also see: Getting 'Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken' when retrieving items from JSON

answered on Stack Overflow Jul 19, 2020 by E. Verdi

User contributions licensed under CC BY-SA 3.0