How to set Locale on GSON (for decimal number separators)

最后都变了- 提交于 2019-12-25 05:13:31

问题


I know you can set date formatting, but how do you set other locale specific stuff like decimal number formatting? (I mean comma vs. dot)


回答1:


Short answer: you don't.

You seem to be somewhat confusing the textual representation of a number and an actual numeric value.

While JSON is a text-based data interchange format, a number (vs. a string) in JSON is a numeric value and is not affected by locale. Section 2.4 of the JSON specification provides the specific definition (emphasis mine):

2.4. Numbers

The representation of numbers is similar to that used in most
programming languages. A number contains an integer component that
may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part.

Octal and hex forms are not allowed. Leading zeros are not allowed.

A fraction part is a decimal point followed by one or more digits.

An exponent part begins with the letter E in upper or lowercase,
which may be followed by a plus or minus sign. The E and optional
sign are followed by one or more digits.

Numeric values that cannot be represented as sequences of digits
(such as Infinity and NaN) are not permitted.

Given the above, something such as {"my_double":3,2} is not valid JSON. {"my_double":3.2} is.

When parsing JSON, a parser is going to store numbers to a primitive data type (int or double). Your locale will then display those properly using the normal methods for converting them to strings; Integer.toString(myInt),String.valueOf(myDouble), etc.



来源:https://stackoverflow.com/questions/19451670/how-to-set-locale-on-gson-for-decimal-number-separators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!