scala 将字符串转换为泛型类型 [英] scala convert String to generic type

查看:51
本文介绍了scala 将字符串转换为泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析一个 json.我想将它的值转换为其他类型.即

I am am parsing a json. I would like to convert it's values to other types . i.e

//json = JSON String 
val seq = net.liftweb.json.parse(json).\\("seq").values.toString.toLong
val userName = net.liftweb.json.parse(json).\\("name").values.toString
val intNum = net.liftweb.json.parse(json).\\("intId").values.toInt

我想使用泛型方法更scala"的方式来转换它,我尝试了这样的事情:

I would like to cast it using generic method more "scala" way, I tried something like this:

object Converter{
  def JSONCaster[T](json:String,s:String):T={
    net.liftweb.json.parse(json).\\(s).values.toString.asInstanceOf[T]
  }
}

但是遇到了铸造错误:

java.lang.ClassCastException: java.lang.String 不能转换为java.lang.Long at scala.runtime.BoxesRunTime.unboxToLong(Unknown来源)

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long at scala.runtime.BoxesRunTime.unboxToLong(Unknown Source)

推荐答案

我遇到了同样的问题,我记得 Play 框架有一些功能可以做类似的事情.在挖掘源代码后,我发现了这个 课程.

I had the same problem and remembered that Play framework had some functionality that did something similar. After digging through the source I found this Class.

基本上,我们可以这样做:

Basically, we can do something like this:

object JSONCaster {

  def fromJson[T](json: String, s: String)(implicit converter: Converter[T]): T = {
    converter.convert(net.liftweb.json.parse(json).\\(s).values.toString)
  }

  trait Converter[T] { self =>
    def convert(v: String): T
  }

  object Converter{
    implicit val longLoader: Converter[Long] = new Converter[Long] {
      def convert(v: String): Long = v.toLong
    }

    implicit val stringLoader: Converter[String] = new Converter[String] {
      def convert(v: String): String = v
    }

    implicit val intLoader: Converter[Int] = new Converter[Int] {
      def convert(v: String): Long = v.toInt
    }

    // Add any other types you want to convert to, even custom types!
  }
}

可以这样称呼:

JSONCaster.fromJson[Long](json, "seq")

缺点是我们必须为我们想要转换的所有类型定义隐式转换器.这样做的好处是使界面非常干净且可重用.

The downside is we have to define implicit converters for all the types we want to cast to. The upside being this keeps the interface really clean and reusable.

这篇关于scala 将字符串转换为泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆