简体   繁体   中英

REST/JSON — field in response is silently incremented by browser?

I'm building a JavaScript application (React/etc.) that consumes REST resources from a companion server (written in Spring Boot/REST/JPA).

Mostly, I'm pulling either lists of entities or single entities --

  • .../rest/tasks?page=0
  • .../rest/tasks/1234567

-- where each entity looks like:

{
  "id" : 20180501150819347,
  "requested" : "2018-05-01T19:08:19.353+0000",
  "cancelled" : null,
  "delayUntil" : null,
  "started" : "2018-05-01T19:08:30.140+0000",
  "ended" : "2018-05-01T19:08:31.610+0000",
  "status" : "complete",
  ...

The Problem is that, for whatever reason, the "id" field on my entity is being incremented!

For example:

1. I make the request: /rest/tasks , to get a list of submitted Tasks.

2. The resulting response looks like:

...
"tasks": [ {
  "id" : 20180501150819347,
  ...

This is correct: a Task entity by that ID does exist in my database.

3. The JSON response is then given to my application as:

...
"tasks": [ {
  "id" : 20180501150819348,
  ...

4. I can definitely retrieve that entity via rest/tasks/...9347 -- but, as in (2) and (3), the resulting JSON object has the incorrect (incremented) ID.

The weird part is: this appears to be happening at the browser -level. When, for instance, I inspect the network request/response in Chrome, I see that the raw response contains the correct ID, and the pretty-printed response contains the incorrect (incremented) ID. I've verified this with both Chrome (66.0.3359.139) and Firefox (59.0.3).

However, this is the only entity-type which manifests such behavior. I've tested all my other entity-types (with both int and long IDs). This behavior is consistent across multiple restarts (both application and browser).

Chrome - response (raw)

Chrome - response (pretty-printed)

You've got a problem with rounding. The number 20180501150819347 is greater than Number.MAX_SAFE_INTEGER . JavaScript (and TypeScript) represent all numbers as floating point numbers, so, numbers greater than that constant can't be correctly represented. Unfortunately, JavaScript does not have a pure integer type, or a long integer.

You can check this behaviour here:

 var num = 20180501150819347; console.log(num); 

As you see, console.log prints the next number, the same that happens to you.

As you're dealing with IDs, my advice is that you change the type of the id property to string . It won't matter on the server-side, but will prevent rounding from ocurring in client side:

...
"tasks": [ {
  "id" : "20180501150819347",
  ...
}, ...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM