How to convert JToken

I have a JToken with value {1234}

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

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

      

+7


source to share


4 answers


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

.



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

      

+31


source


You must use:



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

      

+8


source


You can just cast JToken

before 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 script demo ]

+2


source


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

0


source







All Articles