5

I am receiving the following error while attempting to parse JSON with json4s:

Non-standard token 'NaN': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow

How do I enable this feature?

arosca
  • 469
  • 7
  • 15

3 Answers3

2

Assuming your ObjectMapper object is named mapper:

val mapper = new ObjectMapper()
// Configure NaN here
mapper.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true)

...

val json = ... //Get your json
val imported = mapper.readValue(json, classOf[Thing])  // Thing being whatever class you're importing to.
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
2

@Nathaniel Ford, thanks for setting me on the right path!

I ended up looking at the source code for the parse() method (which is what I should have done in the first place). This works:

import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.ObjectMapper
import org.json4s._
import org.json4s.jackson.Json4sScalaModule

val jsonString = """{"price": NaN}"""

val mapper = new ObjectMapper()
// Configure NaN here
mapper.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true)
mapper.registerModule(new Json4sScalaModule)

val json = mapper.readValue(jsonString, classOf[JValue])
arosca
  • 469
  • 7
  • 15
2

While the answers above are still correct, what should be amended is, that since Jackson 2.10 JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS is deprecated.

The sustainable way for configuring correct NaN handling is the following:

val mapper = JsonMapper.builder().enable(JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS).build();
// now your parsing
mle
  • 2,466
  • 1
  • 19
  • 25
  • Exactly what I was looking for, as I wanted to migrate. As this is a "read" feature, do you happen to know if this also affects writing to json? – Vankog Feb 21 '22 at 08:40
  • Hey @Vankog, yes I know it and no, it does not affect writing. :-) – mle Feb 25 '22 at 08:22