AKADER AKADER - 5 months ago 102
JSON Question

Can't get value from JTOken

I have this JToken

var pv = JToken.Parse(keys["parameterValues"].ToString()).ToList()[0];


Which returns this value

{"DE:Actual Savings": 42217.0}


I can't use .Value because the float is represented as an object
{42217.0}


How can I get this number? Right now I am using .ToString() and converting it

etr etr
Answer

To convert the value to a defined type you could use one of the defined methods below:

System.Convert.ChangeType(jtoken.ToString(), targetType);

or

JsonConvert.DeserializeObject(jtoken.ToString(), targetType);

Let's take into consideration our sample:

string json = @{"DE:Actual Savings": 42217.0}

You could do something like:

var obj = (JObject)JsonConvert.DeserializeObject(json);
Type type = typeof(float);
var i1 = System.Convert.ChangeType(obj["DE:Actual Savings"].ToString(), type);

Hope this solves your problem.