minimal-json
minimal-json copied to clipboard
Support creating JSON numbers from custom types like BigDecimal
Making JsonNumber
public would allow to create JSON numbers that does not fit into any of the primitive Java types. Examples would be numbers with arbitrary precision, e.g. BigInteger and BigDecimal. Alternatively, factory methods could be offered for these two types.
Thanks, Janosch. I'm afraid that opening up this API would entail requests for other Number types like Integer, Long, Float, Double, etc. and the API would explode. There may even be custom subtypes of Number. Wouldn't it be acceptable to create instances of those types manually, like:
new BigInteger( jsonValue.toString() )
To add a BigInteger to a JSON structure, we could either open up JsonNumber:
jsonArray.add( new JsonNumber( bigInt ) )
or accept Numbers and rely on toString
to return a valid JSON number string (would require checks):
JsonValue.valueOf( bigInt )
and
jsonArray.add( bigInt )
As I see this, we have JsonNumber, for which we have methods like asInt, asLong and asFloat. Since BigDecimal is implemented in the Java standard libraries and you just have no non-imprecise number accessible from JsonNumber, it would be straight-forward to me to use BigDecimal. As I fas remember I used this in the context of monetary values and there you can't rely on types like float or double since they round in "non-human ways". So my concern was just to add the a method "asDecimal" which would return the encoded values as BigDecimal.
I mean the value is encoded as string in JSON anyway, so why not offer a way to get this number without rounding. And of course I could just do "new BigInteger(jsonValue.toString())", but that's not as clean.
So, primarily I don't see a point, where datatypes for numbers from the Java standard library shouldn't be supported by JsonNumber, since the json number type doesn't specify a particular type (like float or double).