TBA
TBA

Reputation: 1187

How to convert a JToken

I have a JToken with the value {1234}

How can I convert this to an Integer value as var totalDatas = 1234;

var tData = jObject["$totalDatas"];
int totalDatas = 0;
if (tData != null)
   totalDatas = Convert.ToInt32(tData.ToString());

Upvotes: 31

Views: 50030

Answers (4)

Luke
Luke

Reputation: 21

try this: int value = (int)token.Value;

Upvotes: 2

har07
har07

Reputation: 89285

You can simply cast the JToken to int :

string json = @"{totalDatas : ""1234""}";
JObject obj = JObject.Parse(json);
JToken token = obj["totalDatas"];
int result = (int)token;

//print 2468
Console.WriteLine(result*2);

[.NET fiddle demo]

Upvotes: 7

Jevgeni Geurtsen
Jevgeni Geurtsen

Reputation: 3133

You should use:

int totalDatas = tData.Value<Int32>();

Upvotes: 14

Sam Harwell
Sam Harwell

Reputation: 99869

You can use the JToken.ToObject<T>() method.

JToken token = ...;
int value = token.ToObject<int>();

Upvotes: 80

Related Questions