arosca
arosca

Reputation: 537

How do I set Jackson parser features when using json4s?

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?

Upvotes: 6

Views: 4745

Answers (3)

mle
mle

Reputation: 2542

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

Upvotes: 2

arosca
arosca

Reputation: 537

@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])

Upvotes: 2

Nathaniel Ford
Nathaniel Ford

Reputation: 21230

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.

Upvotes: 2

Related Questions