Monday, September 24, 2018

How to convert object to JSON of an integer field having leading zeros using Jackson?

Question:
When I try to convert an object having an integer field with value as 0000, the converted JSON contains 0 instead of 0000.
How can I configure Jackson's ObjectMapper to convert 0000 to 00000?
Answer:
A leading 0 indicates an octal number. Hence leading zeros are not allowed for numeric values in JSON. See the following quote from the RFC 7159:
The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It 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. Leading zeros are not allowed.
If you need leading zeros, consider using a string.

No comments:

Post a Comment

Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...