Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parsing a long value leads to different value as double #1065

Closed
dstrasse opened this issue Apr 12, 2017 · 2 comments
Closed

Parsing a long value leads to different value as double #1065

dstrasse opened this issue Apr 12, 2017 · 2 comments

Comments

@dstrasse
Copy link

Hi,
my REST response contains something like

"myId":7000000000000125407
The JSON is a little bit more complex so a Map is used as the basic data type.
Unfortunately, the value for my given ID will be a different one after parsing since Gson casts to double directly which leads to the following value in my map:

(double)7000000000000125407l -> 7.0000000000001249E18

Unfortunately, the JSON is supplied by a 3rd party system and cannot be modified, so I cannot add quotes. A way to enforce Strings for defined types would be great.

@pakopa
Copy link

pakopa commented Apr 21, 2017

When no data type is specified, gson reads al numbers as doubles (see: com.google.gson.internal.bind.ObjectTypeAdapter:78-79) and there is no way to plug a custom ObjectTypeAdapter since it is designed taht way (see: com.google.gson.internal.bind.ObjectTypeAdapter:198-208)

I think there should be a way to define a custom ObjectTypeAdapter

In the meantime I managed to come with the following workaround.

  1. Define a custom empty class that will be used as a flag for deserialization.
  2. Copy the implementation of ObjectTypeAdpater and modify the deserialization. (I went for bigdecimals)
  3. Register a typeAdapterFactory that instantiates your ObjectTypeAdapter for the flag class in the GsonBuilder creating your gson object.
  4. Deserialize with Object o = gson.fromJson(reader, YourFlagClass.class) (thanks type erasure)

I had to twist the API way too much for something that should be easily achievable.

@eamonnmcmanus
Copy link
Member

Fixed by #1290.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants