Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Json.Net JValue to int

Tags:

c#

json.net

I've tried:

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

But this only seems to be valid for JObjects. Is there a way to get the integer from a JValue?

like image 969
trees_are_great Avatar asked May 22 '15 09:05

trees_are_great


Video Answer


2 Answers

Maybe this helps you along:

int storedValue = myJValue.ToObject<int>(); 
like image 92
stefankmitph Avatar answered Oct 25 '22 04:10

stefankmitph


For anyone interested in Performance, Value() is much much quicker 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);
    }
like image 23
Will Calderwood Avatar answered Oct 25 '22 05:10

Will Calderwood