Read value from nested Json object

-1

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.

c#
json
parsing
asked on Stack Overflow Jul 19, 2020 by hyperdanny

2 Answers

1

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
0

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