我正在寻找一种通用的函数方法,可以在Scala字符串与任何数字类型之间进行转换。如果无法通过默认值,我需要。
例如,我需要从转换为String,Int但万一将String转换为Int失败。我需要传递默认值而无需throws java.lang.NumberFormatException。我尝试过这种方式,但是没有得到我的想法,因为我需要通用的,并且在出现异常的情况下也使用默认值
I have a JSON string and I created a function which parses this JSON as an object using Scala case class. I wrote the below code to parse it in a generic way. However, It gave me an error:
def getJsonObj[T](jsonString:String): T = {
implicit val formats: DefaultFormats.type = DefaultFormats
parse(jsonString).extract[T]
}
Run Code Online (Sandbox Code Playgroud)
Error can be found below:
Error:(19, 32) No Manifest available for T.
parse(jsonString).extract[T] Error:(19, 32) not enough arguments for
method extract: (implicit formats: org.json4s.Formats, implicit mf:
scala.reflect.Manifest[T])T. …Run Code Online (Sandbox Code Playgroud)