David
David

Reputation: 1296

JSON return from a web API can be double or long, how do I most efficiently deal with this in Java?

I'm writing some code in java and using the JSON Simple package. I run this code below

jsonObject.get( "last" ) ;

Unfortunately this can either be a long or a double, what is the fastest/most correct way of parsing this value?

Would it be something like the following?

long lngLast = -1;
double dblLast = -1;

if ( jsonObject.get( "last" ).getClass().getName() == "java.lang.Long" ) {
    lngLast =  (long) jsonObject.get( "last" ) ;
} else {
    dblLast = (double) jsonObject.get("last");
}

if ( lngLast == -1)
    System.out.println( dblLast );
else
    System.out.println( lngLast );

This seems absurd. There must be a better way of doing this. I've attempted converting the long to a double (which I believe I am supposed to be able to do?) but I get errors every time. I'm hoping someone can educate me on the correct or better way to do this.

Upvotes: 1

Views: 1745

Answers (1)

jakson
jakson

Reputation: 782

In reality, the "last" element should have a consistent data type in all the JSON messages you're dealing with. Without a proper spec and without wanting to test, you'd probably want to go with double over a long.

In the case you have, where the type can be either, I think testing the object type is a perfectly fine way to do it.

As a side note, your if test should really be:

if (jsonObject.get("last").getClass().equals(Long.class)) {
    ....
}

Using == for String comparison will not work as you'd want it to.

Upvotes: 5

Related Questions