scalajson4s

Json4s unable to desrialize in scala


I need a help in json desrialization in scala using Json4s. I get the following error when I try to desrialize the json

scala.collection.immutable.Map$Map1 cannot be cast to 
 LocationServiceTest$$anonfun$1$LocationList$3
 java.lang.ClassCastException: scala.collection.immutable.Map$Map1 cannot be cast to 
 LocationServiceTest$$anonfun$1$LocationList$3
at LocationServiceTest$$anonfun$1.apply$mcV$sp(LocationServiceTest.scala:34)
at LocationServiceTest$$anonfun$1.apply(LocationServiceTest.scala:16)
at LocationServiceTest$$anonfun$1.apply(LocationServiceTest.scala:16)

My Json as follows :

    {
  "locations" : [
    {
      "country": "YY",
      "placeName": "YY",
      "latitude": "YY",
      "longitude": "YY"
    },
    {
      "country": "XX",
      "placeName": "XX",
      "latitude": "XX",
      "longitude": "XX"
    },

My code :

case class Location(country: String, placeName: String, latitude: Double, longitude: Double)
 val locations = parse(scala.io.Source.fromFile("input.json").mkString)
  println(locations.values.asInstanceOf[LocationList])

Using extract(format, manifest) also fails.. Can someone please help.


Solution

  • The code is shown below:

    object Test extends App {
      import org.json4s._
      import org.json4s.jackson.JsonMethods._
      implicit val formats =DefaultFormats
    
      val str = scala.io.Source.fromFile("input.json").mkString
    
      case class Location(country: String, placeName: String, latitude: String, longitude: String)
    
      val dataObj= parse(str)
      val locObj = (dataObj \ "locations").extract[Seq[Location]]
    
      println(locObj)
    }
    

    The output:

    List(Location(YY,YY,YY,YY), Location(XX,XX,XX,XX))
    

    Note that in case class, latitude and longitude are string since in json, you declared them as string.

    Let me know if it helps!!