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",
    
    "Data":
    {
        "ID":
        {
            "value": "0008044834"
        },
        "Carrier":
        {
            "value": 0
        },
        "Tool":
        {
            "value": 0
        }
    }
}
          var myJsonString = File.ReadAllText(_currentDictory.FullName + @"\test\" + completeFilename);
            var myJObject = JObject.Parse(myJsonString);
            var serial = myJObject.SelectToken("Data.ID").Value<String>();
System.InvalidCastException
  HResult=0x80004002
  Message=Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken.
  Source=Newtonsoft.Json
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.
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.
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>();
 E. Verdi
 E. VerdiUser contributions licensed under CC BY-SA 3.0