How to convert a JToken

烂漫一生 提交于 2020-01-12 19:03:54

问题


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());

回答1:


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

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



回答2:


You should use:

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



回答3:


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]




回答4:


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



来源:https://stackoverflow.com/questions/25870698/how-to-convert-a-jtoken

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!