trees_are_great
trees_are_great

Reputation: 3911

Converting Json.Net JValue to int

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?

Upvotes: 24

Views: 34503

Answers (4)

Will Calderwood
Will Calderwood

Reputation: 4636

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

Upvotes: 21

RonC
RonC

Reputation: 33851

There are good answers here already but I want to add one more that people may find useful. If you have a List<JValue>, let's call it myJValueList and the JValue objects in the list are internally holding an int then you can get that int doing the following:

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

Upvotes: 0

Vincent
Vincent

Reputation: 3509

int storedValue = (int)myJValue;

Upvotes: 2

stefankmitph
stefankmitph

Reputation: 3306

Maybe this helps you along:

int storedValue = myJValue.ToObject<int>(); 

Upvotes: 45

Related Questions