Given a JToken
called distance with the following content
{ "232": { "travelDistance": 25.0 } }
I would like to read the field travelDistance from it. First I tried this
distance.TryGetPropertyValue("travelDistance", float.MaxValue)
but this returns the fallback value float.MaxValue
. Then I tried to use a JSON path
distance.SelectToken("$.travelDistance")
but this returns null
. These are my debugging results
How can I read the value of the property travelDistance?
With JObject
you can read the field values
var jObj = JObject.Parse(jsonString);
var result = Convert.ToDecimal(jObj["232"]["travelDistance"]);
OR
var result1 = Convert.ToDecimal(jObj.SelectToken("232.travelDistance"));
OR
var result2 = Convert.ToDecimal(jObj.SelectToken("*.travelDistance"));
OR
var result3 = jObj.SelectTokens("*.travelDistance")
.Select(x => Convert.ToDecimal(x))?
.FirstOrDefault();