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

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

package com.github.kondaurovdev.json.j4s

import java.io.FileInputStream

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

class TryHelperJson4s extends json_iface.TryHelperIface[JValue]   {

  def blockToEither[R](block: => R): Either[JValue, R] = {
    util.Try(block).toEither.left.map(e => JString(e.getMessage))
  }

  def tryBlock[R](block: => R, errMsg: JValue): Either[JObject, R] = {
    blockToEither(block).left.map(err => {
      JObject(List(
        ("errorMsg", errMsg),
        ("error", err)
      ))
    })
  }

  def parse2Either(s: String): Either[JObject, JValue] = {
    tryBlock(JsonMethods.parse(s), JString("Can't parse json"))
  }

  def parseFile(filePath: String): Either[JObject, JValue] = {
    tryBlock(JsonMethods.parse(new FileInputStream(filePath)), JString("Can't parse json from file"))
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy