AKADER AKADER - 1 year ago 244
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

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

etr etr
Answer Source

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

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


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.