How do I set Jackson parser features when using json4s?
Asked Answered
I

3

6

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?

Italia answered 24/8, 2016 at 21:36 Comment(1)
Don't forget to upvote/accept answers if they helped you! You'll be more likely to get help in the future.Costard
C
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.
Costard answered 24/8, 2016 at 21:38 Comment(2)
Hm... I think my error happens when I read the JSON document though: val json = parse(jsonString)Italia
@Italia I'm afraid without more context/code I can't entirely see the relation.Costard
I
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])
Italia answered 29/8, 2016 at 13:9 Comment(0)
S
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
Scutellation answered 17/2, 2021 at 13:58 Comment(2)
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?Finbur
Hey @Vankog, yes I know it and no, it does not affect writing. :-)Scutellation

© 2022 - 2024 — McMap. All rights reserved.