Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a JToken

Tags:

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());
like image 502
TBA Avatar asked Sep 16 '14 13:09

TBA


People also ask

Is JToken a JArray?

As stated by dbc, a JToken that represent a JArray, is already a JArray. That is if the JToken. Type equals an JTokenType.

What is JToken?

JToken is the abstract base class of JObject , JArray , JProperty , and JValue , which represent pieces of JSON data after they have been parsed. JsonToken is an enum that is used by JsonReader and JsonWriter to indicate which type of token is being read or written.

What does JToken parse do?

Parse() to parse a JSON string you know to represent an "atomic" value, requiring the use of JToken. Parse() in such a case. Similarly, JToken. FromObject() may be used to serialize any sort of c# object to a JToken hierarchy without needing to know in advance the resulting JSON type.


2 Answers

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

JToken token = ...;
int value = token.ToObject<int>();
like image 118
Sam Harwell Avatar answered Oct 25 '22 13:10

Sam Harwell


You should use:

int totalDatas = tData.Value<Int32>();
like image 31
Jevgeni Geurtsen Avatar answered Oct 25 '22 12:10

Jevgeni Geurtsen