com.github.kondaurovdev.json.j4s.YamlHelperJson4s.scala Maven / Gradle / Ivy
package com.github.kondaurovdev.json.j4s
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.{YAMLFactory, YAMLGenerator, YAMLMapper}
import com.github.kondaurovdev.json_iface.YamlHelperIface
import org.json4s.JsonAST.{JString, JValue}
import org.json4s.jackson.JsonMethods._
trait iYamlHelperJson4s extends YamlHelperIface[JValue] {
def tryHelper: TryHelperJson4s
def mapper: YAMLMapper
def factory: YAMLFactory
def parse(input: String): Either[JValue, JValue] = {
for {
json <- {
tryHelper.tryBlock({
val reader = new ObjectMapper(factory)
val value = reader.readTree(input)
val jsonWriter = new ObjectMapper()
jsonWriter.writeValueAsString(value)
}, JString("Cant convert yaml to json"))
}
res <- tryHelper.parse2Either(json)
} yield res
}
def asYaml(json: JValue): Either[JValue, String] = {
tryHelper.tryBlock({
val node = asJsonNode(json)
mapper.writeValueAsString(node)
}, JString("Can't convert json to yaml"))
}
}
object YamlHelperJson4s {
def defaultMapper: YAMLMapper = {
new YAMLMapper()
.configure(YAMLGenerator.Feature.WRITE_DOC_START_MARKER, false)
.configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true)
}
def defaultFactory: YAMLFactory = {
new YAMLFactory()
}
}
class YamlHelperJson4s(
val tryHelper: TryHelperJson4s,
val mapper: YAMLMapper = YamlHelperJson4s.defaultMapper,
val factory: YAMLFactory = YamlHelperJson4s.defaultFactory
) extends iYamlHelperJson4s