'Convert Int in Request Body to Long always

I wrote my backend in Java, and the endpoint is hit with a request body. The endpoint has a JSON body that looks like this

{"id": 1234, "data": {...}}

Now, I'm getting the request data, and storing it by the id. I want to save the ids' as longs, however, the values can be anywhere from int-valid to long-valid.

I'm using the Spring framework in order to save it. The function looks like this

public String getData (@RequestBody JSONObject jsonRequest) {
    Long id_long = (Long) jsonRequest.get("id"); 

However, I get this error

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

This is where I'm stuck. Sometimes the id value will be valid like 1234L, or a really long number which is in long range. However, sometimes it is int range. I haven't used Java that much so I was wondering how to do the cast properly so I always get a long.



Solution 1:[1]

The simple answer is to use a java.lang.Number object, which is the superclass of the Long and Integer classes. It has a longValue() method to get the value as a long every time.

public String getData (@RequestBody User user) {
    Long id_long = ((Number) jsonRequest.get("id")).longValue();

The longer answer would be not to use a generic class like JSONObject. Define your own class, and use spring to bind to it...

public class User {
    private long id;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }
}

public String getData (@RequestBody User user) {
    Long id_long = user.getId(); 

Solution 2:[2]

Integer has a longValue method that returns the value as a long (primitive). You can assign it to id_long and let the autoboxing wrapping it into a Long.

public String getData (@RequestBody JSONObject jsonRequest) {
    Long id_long = jsonRequest.get("id").longValue();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Spotted
Solution 2 Spotted