0

I made a Restful API with Spring Boot. One of my methods is a delete that takes the Response object and does some other queries eventually deleting the object from the DB depending on conditions. However, it is failing before the function body due to a type mismatch trying to convert String to Long.

I am using JSON in the request which does not use the Long type, so I use a string like this "id":"1" instead, which won't convert for some reason. Does anyone have a suggestion?

Response Object:

public class Response {

    private long id;
    private String key;
    private String value;
    private String group;
 
 
    public Response(String key, String value, String group) {
         this.key = key;
         this.value = value;
         this.group = group;
    }

I use a GeneratedValue(strategy = GenerationType.IDENTITY) to auto-create IDs.

It seems to fail when attempting to convert the JSON to a Response object:

public ResponseEntity<String> deleteResponse(@RequestBody Response response) {

}
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • Is there reason you don't use a JSON number? `"key": 1` – Billy Brown Mar 30 '21 at 20:41
  • 1
    @BillyBrown I believe that rounding happens during conversion as JSON doesn't support long. Can anyone confirm? – Keenan Hillerbrand Mar 30 '21 at 20:43
  • It depends on how large the number gets. JSON numbers are probably parsed as `float` or `double` in Java, which can still represent a large number of `long`s. It mostly depends on how large you expect the ids to get. Otherwise, if you want to use a string for exactness, then change the internal type to a `String` (which you could convert internally further down the line), or add some custom parsing in there (unfortunately I can't say how to do that). – Billy Brown Mar 30 '21 at 20:48
  • 1
    This might help (in both directions): https://stackoverflow.com/questions/4268872/how-to-serialize-long-to-string-with-jackson (see the comment: "the other way around is `@JsonDeserialize(as = Long.class)`" – Thomas Mar 30 '21 at 20:52
  • 2
    @KeenanHillerbrand You're correct; the exact range of a JSON Number is ±2^52. In general, it's recommended to treat `id` fields as opaque strings everywhere, so that clients don't do dumb things based on whether they're integer/UUID/whatever. – chrylis -cautiouslyoptimistic- Mar 30 '21 at 20:52

1 Answers1

-1

You should not pass "id":"1" if you want auto-conversion. You should pass the JSON using "id": 1 (without quotes on the number).

the Tin Man
  • 158,662
  • 42
  • 215
  • 303