All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.kondaurovdev.json.j4s.JValueHelperJson4s.scala Maven / Gradle / Ivy

package com.github.kondaurovdev.json.j4s

import com.github.kondaurovdev.json_iface.JValueHelperIface
import org.json4s.JsonAST.{JObject, JString}
import org.json4s.jackson.JsonMethods._
import org.json4s.{Formats, JsonAST}

class JValueHelperJson4s(
  tryHelper : TryHelperJson4s,
  formats: Formats
) extends JValueHelperIface[JsonAST.JValue] {

  def compactPrint(v: JsonAST.JValue): String = {
    compact(render(v))
  }

  def prettyPrint(js: JsonAST.JValue): String = {
    pretty(render(js))
  }

  def get(js: JsonAST.JValue)(path: String): Either[JsonAST.JValue, JsonAST.JValue] = {

    tryHelper.tryBlock({
      js \ path
    }, JString(s"Path '$path' doesn't exist"))

  }

  def castTo[M](js: JsonAST.JValue)(implicit impl: Manifest[M]): Either[JObject, M] = {
    tryHelper.tryBlock({
      js.extract[M](formats, manifest)
    }, JString(s"Can't cast json to type ${manifest.runtimeClass.getSimpleName}"))
  }

  def getAndCast[M](js: JsonAST.JValue)(path: String)(implicit manifest: Manifest[M]): Either[JsonAST.JValue, M] = {
    for (
      value <- get(js)(path);
      res <- castTo[M](value).right
    ) yield res
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy