Skip to content

Instantly share code, notes, and snippets.

@cgruber
Last active September 16, 2020 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgruber/5c021f22bf9ed30bdcf1bf88baee2b7c to your computer and use it in GitHub Desktop.
Save cgruber/5c021f22bf9ed30bdcf1bf88baee2b7c to your computer and use it in GitHub Desktop.
Exposing DumperOptions in Jackson's YAML handling.
// See article for context: http://www.geekinasuit.com/2020/09/jackson-yaml-and-kotlin-data-classes.html
// Licensed under the MIT license described here: https://choosealicense.com/licenses/mit/
// Copyright (c) Square, Inc.
val jacksonMapper = YAMLMapper(MyYAMLFactory()).apply {
registerModule(KotlinModule())
setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
}
)
// I left the constructor parameters nullable deliberately
class MyYAMLGenerator(
ctx: IOContext?,
jsonFeatures: Int,
yamlFeatures: Int,
codec: ObjectCodec,
out: Writer?,
version: DumperOptions.Version?
): YAMLGenerator(ctx, jsonFeatures, yamlFeatures, codec, out, version) {
override fun buildDumperOptions(
jsonFeatures: Int,
yamlFeatures: Int,
version: Version?
): DumperOptions {
return super.buildDumperOptions(jsonFeatures, yamlFeatures, version).apply {
defaultScalarStyle = ScalarStyle.LITERAL;
defaultFlowStyle = FlowStyle.BLOCK
indicatorIndent = 2
nonPrintableStyle = ESCAPE
indent = 4
isPrettyFlow = true
width = 100
this.version = version
}
}
}
class MyYAMLFactory(): YAMLFactory() {
@Throws(IOException::class)
override fun _createGenerator(out: Writer, ctxt: IOContext): YAMLGenerator {
val feats = _yamlGeneratorFeatures
return MyYAMLGenerator(ctxt, _generatorFeatures, feats, _objectCodec, out, _version)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment