scala convert String to generic type


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

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] } }

but got casting error :


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



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 <a href="https://github.com/playframework/playframework/blob/dc0b930065ca62b876370c9b2cd51d0a6495c980/framework/src/play/src/main/scala/play/api/Configuration.scala#L1014" rel="nofollow">Class</a>.

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! } }

Can be called like:

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.


Take a look at <a href="http://spray.io/documentation/1.2-M8/spray-httpx/marshalling/" rel="nofollow">marshalling/unmarshalling</a> as implemented in Spray. You may not need to reinvent the solution, and if you do, you can take a look at <a href="https://github.com/spray/spray/blob/release/1.2/spray-httpx/src/main/scala/spray/httpx/unmarshalling/Deserializer.scala" rel="nofollow">their source</a> to see how they've implemented it.

Spray's marshalling/unmarshalling is similar to object graph serialization and works with more than just JSON so there's some additional inherent complexity within the implementation.

You could also get around manually parsing JSON and try <a href="https://github.com/lift/lift/tree/master/framework/lift-base/lift-json/" rel="nofollow">lift-json</a>.

lift-json is closer to JSON though through <a href="https://github.com/lift/lift/tree/master/framework/lift-base/lift-json/#extracting-values" rel="nofollow">extract</a> it can operate similar to Spray's marshaller/unmarshaller.


The best and nice solution I found is at <a href="http://www.derekwyatt.org/2011/09/01/heres-one-of-the-reasons-why-monads-are-awesome/" rel="nofollow">Derek Wyatt's Blog -heres one of the reasons why monads are awesome</a>


  • Get Xpath from command line in scala
  • In Scala, how to infer one type parameters of a def?
  • Compute size of Spark dataframe - SizeEstimator gives unexpected results
  • Functional code for looping with early exit
  • How to add key values into decoded json in PHP?
  • Exporting nested fields with invalid characters from Spark 2 to Parquet [duplicate]
  • how to get video image url in youtube using json
  • How to test a public method in an akka actor?
  • how to create EdgeRDD from data frame in Spark
  • scala convert String to generic type
  • Implicit parameters break type inference or inference does not suffice for their resolution?
  • java.lang.ClassCastException: javax.faces.component.StateHolderSaver cannot be cast to [Ljava.lang.O
  • Remote interface cannot be cast to EJB container
  • Get Items in a PurchaseOrder using SuiteTalk
  • Bypassing grails view resolvers?
  • How do I find the Java interface whose method is implemented in a given class?
  • Casting JSONArray to Iterable - Kotlin
  • Scala, gremlin-scala, HLists, Poly2, RightFold and a missing implicit Prepend
  • Ruby on Rails App deployed to heroku showing “We're sorry, but something went wrong”
  • Detecting null parameter in preprocessor macro
  • C# program and C++ DLL compiled for 32-bit system crash on 64-bit system
  • What does 'Language neutral' mean with regard to MAKELANGID?
  • Problem deserializing objects from cache on MyBatis 3/Java
  • print() is showing quotation marks in results
  • Content-Length header not returned from Pylons response
  • Play WS (2.2.1): post/put large request
  • How to access EntityManager inside Entity class in EJB3
  • Display issues when we change from one jquery mobile page to another in firefox
  • vba code to select only visible cells in specific column except heading
  • Python - Map / Reduce - How do I read JSON specific field in using DISCO count words example
  • Hibernate gives error error as “Access to DialectResolutionInfo cannot be null when 'hibernate.
  • coudnt use logback because of log4j