Search code examples
jsonrestspring-mvcjacksonjackson-modules

How to JsonFormat long value with commas


I have a front-end I created that allows for a numeric value. Of course, the value the user should enter should strictly be a numeric value. That is no decimal, no commas, no $, no other values, and I can control this on the UI if I need to.

However, in the case the user does enter free text in this numeric box, I am looking for an easy way to convert 123,456 to just 123456.

I am using Spring 5, Spring MVC, and the REST Controller works fine if I am passing into it '123456', however, because the POJO has a long value, I am wondering if I can with Jackson FasterXML use @JsonFormat annotation to take 123,456 and convert that to 123456????

Let's say someone enters in 123,456,789.00 as a value, and we know this can be converted to a long, so I wonder if we could use the @JSonFormat annotation on this field to make it convert to 123456789???

Is there something I could do in the setter of the POJO to make this work?

I suppose I could also just change my POJO to accept a String value, and then remove all commas, all decimals, remove $, remove any other non numeric values, and then would be the catch-all.

Thanks!


Solution

  • I'm afraid to tell you, but there is no way to achieve this with @JsonFormat.

    Two possible approaches are described in the first two answers of the question How to deserialize a float value with a localized decimal separator with Jackson, as they are:

    • Implementing a custom JSON deserializer with the logic you described with your words: […]and then remove all commas[…]

    • Using a localized DefaultDeserializationContext which parses the number included in your strings depending on the given Locale