Convert Json.Net JValue to int

I tried:

JValue myJValue = getJValue(someVar); int storedValue = JsonConvert.DeserializeObject(myJValue); 

But this only seems fair for JObjects. Is there a way to get an integer from JValue?

+7
source share
4 answers

Perhaps this will help you:

 int storedValue = myJValue.ToObject<int>(); 
+20
source

int storedValue = (int) myJValue;

+2
source

There are good answers here, but I want to add one more thing that people may find useful. If you have a List<JValue> , let it myJValueList and the myJValueList objects in this list internally contain int then you can get int do the following:

 foreach(int myInt in myJValueList){ //do some work with the myInt } 
0
source

For anyone interested in Performance, Value() much faster than ToObject() . For strings just use ToString()

Int test:

 value.Value<int>() - 2496ms value.ToObject<int>() - 6259ms 

Double test:

 value.Value<double>() - 572ms value.ToObject<double>() - 6319ms 

String Test:

 value.Value<string>() - 1767ms value.ToObject<string>() - 6768ms value.ToString() - 130ms 

,

  private static void RunPerfTest() { int loops = 100000000; JValue value = new JValue(1000d); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < loops; i++) { double x = value.Value<double>(); } sw.Stop(); Console.WriteLine("value.Value<double>()" + sw.ElapsedMilliseconds); sw.Restart(); for (int i = 0; i < loops; i++) { double x = value.ToObject<double>(); } sw.Stop(); Console.WriteLine("value.ToObject<double>()" + sw.ElapsedMilliseconds); } 
0
source

All Articles