Search code examples
scalalift-json

JSON deserialization using reflection


Hi I am trying to extract a JSON using reflection

import net.liftweb.json._
case class Bike(make: String, price: Int) {
   def this(price: Int) = this("Trek", price)
}

val cls = Class.forName("Bike")
val manifest = Manifest.classType(cls)
val parsedData =net.liftweb.json.JsonParser.parse(json)

JsonParser.parse(""" {"price":350} """).extract[manifest]

however I am getting this error:

not found: type manifest
  JsonParser.parse(""" {"price":350} """).extract[manifest]
                                                   ^

although manifest is from type Manifest


Solution

  • You can extract directly into a case class

    val json = "the json";
    
    val bike = parse(json).extract[Bike];
    

    JSON parsing is done through reflection.

    If the class is a runtime construct, create a TypeInfo instance and pass that to the extract method.