Search code examples
scalagenericsjson4s

Scala generics usage for methods + json4s parsing


I am not sure if this is achievable and I have a very basic understanding of how generics work in scala. But I was wondering if this is possible. Say I have a method:

case class Person(id:String,name:String)
case class Student(id:String,name:String, class:String)

    def convertToJson[A](fileName:String):{
     //read file
     parse[A]
    }

Is it possible to write this generic method which would parse the json based on the type of class I send when I call the convertToJson method? Something like:

convertToJson[Student](fileName)
convertToJson[Person](fileName)

BTW the above code gives me a :

No Manifest available for A. error.

Using json4s for parsing. Any help is appreciated.


Solution

  • This will convert a JSON string to a case class

    import org.json4s._
    import org.json4s.jackson.JsonMethods._
    
    def convertToJson[T](json: String)(implicit fmt: Formats = DefaultFormats, mf: Manifest[T]): T =
      Extraction.extract(parse(json))
    

    Once this is defined you can parse appropriate strings to the required type:

    case class Person(id: String, name: String)
    case class Student(id: String, name: String, `class`: String)
    
    val person = convertToJson[Person]("""{"name":"Jane","id":45}""")
    val student = convertToJson[Student]("""{"name":"John","id":63, "class": "101"}""")
    

    Note that this will ignore JSON data that does not match fields in the case class. If a field is optional in the JSON, make it an Option in the case class and you will get None if the field is not there.