Skip to content

Commit

Permalink
json: allow mapper to be customized (#1656)
Browse files Browse the repository at this point in the history
Provide method that can be used to customize the mapper.
This should be used carefully as it will impact all uses
of `Json` and could break other aspects that rely on the
default behavior.
  • Loading branch information
brharrington authored May 6, 2024
1 parent f50992c commit 2216b69
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
10 changes: 10 additions & 0 deletions atlas-json/src/main/scala/com/netflix/atlas/json/Json.scala
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,16 @@ object Json {
smileMapper.registerModule(module)
}

/**
* Can be called to alter the configuration of the default mapper. Note, this will
* cause changes to apply everything using this object which could break things that
* expect the default behavior.
*/
def configure(f: ObjectMapper => Unit): Unit = {
f(jsonMapper)
f(smileMapper)
}

def newMapper: ObjectMapper = newMapper(jsonFactory)

def newJsonGenerator(writer: Writer): JsonGenerator = {
Expand Down
20 changes: 19 additions & 1 deletion atlas-json/src/test/scala/com/netflix/atlas/json/JsonSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@ import java.math.BigInteger
import java.util
import java.util.Optional
import java.util.regex.Pattern

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.core.JsonToken
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.SerializationFeature
import munit.FunSuite

import java.time.Instant

/**
* Test case for the capabilities we need from a json parser. Mostly to document what we are using
* and ease transition to alternative libraries if we want to switch.
Expand Down Expand Up @@ -473,6 +475,22 @@ class JsonSuite extends FunSuite {
val obj = JsonObjectWithSupport(42.0)
assertEquals(Json.encode(List(obj)), """[{"custom":42.0}]""")
}

test("customize mapper") {
val now = Instant.now()
assertEquals(Json.encode(now), now.toEpochMilli.toString)

try {
Json.configure { mapper =>
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
}
assertEquals(Json.encode(now), s"\"${now.toString}\"")
} finally {
Json.configure { mapper =>
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true)
}
}
}
}

case class JsonKeyWithDot(`a.b`: String)
Expand Down

0 comments on commit 2216b69

Please sign in to comment.