When working with JSON (or variant in general), it can sometimes happen that the type in JSON is smaller than the type I want to get via casting. Currently this will throw an exception. For example:
Something like the above is pretty common (although simplified a lot) - grab an ID from each object in a list. The first one will work fine, but the second one will fail with java.lang.ClassCastException -> Cannot cast java.lang.Integer to java.lang.Long exception because the second ID will be parsed as integer.
I know that I can catch the exception and inline the cast, but that still makes it quite annoying to deal with it:
Please extend casting so that it can do safe upcasting without throwing an exception. I would imagine that the following casts would work fine:
- integer to long
- integer to decimal
- long to decimal
- number to decimal
"Questionable" casts (i.e. those where I'm not sure whether I'd want that or not):
- Any type into string (basically would call "toString" on the value). This can be nice to have, but on the other annoying if dealing with locale (since it would necessarily use default locale and that can be different than what is expected in given situation).
- boolean to integer (or long): true = 1, false = 0
- boolean to number
- boolean to decimal
Other casts (e.g. integer to string. string to integer etc.) would still throw an exception and would need to be handled by the developer.
Note that it is possible to extend this even further to provide casting that tries the cast and if it works it would also allow downcasts. For example a long that fits into an integer can be safely cast while large numbers would throw an exception.