0

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.

Ethan
  • 821
  • 4
  • 12
Saawan
  • 363
  • 6
  • 24

2 Answers2

2

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

Anand Sai
  • 1,566
  • 7
  • 11
1

The parse function creates JValue (JSON representation in Scala types, like Map, Array and primitive types). That type is not in any way related to some custom type, like LocationList. For that you need to use json.extract. See https://github.com/json4s/json4s Extracting values:

Case classes can be used to extract values from parsed JSON

json.extract[Person]

Community
  • 1
  • 1
Suma
  • 33,181
  • 16
  • 123
  • 191