user3887341 user3887341 - 1 month ago 12
JSON Question

Scala mapping Json and case class

now I'm trying to parse json to case class, and I have a problem.
This is my json string:

{"book_id":"1", "book_name":"Skype", "author_name":"bla bla", "author_country":"Poland"}


And I have 2 case classes:

case class Book(bookId: String, bookName: String){}
case class Author(authorNam: String, authorCountry: String){}


So how can I parse the Json into 2 classes?
The output will be:

Book(1, Skype)
Author(bla bla, Poland)


Thank you so much for your help.

Answer

There are a few solutions for you, the most obvious of them:

  1. Json4s (it supports jackson)

  2. Spray-Json is a lightweight, clean and efficient JSON implementation in Scala.

UPD Let's consider usage of Json4s:

  object JsonExample extends App {

  import org.json4s._
  import org.json4s.JsonDSL._
  import org.json4s.jackson.JsonMethods._

  case class Winner(id: Long, numbers: List[Int])
  case class Lotto(id: Long, winningNumbers: List[Int], winners: List[Winner], drawDate: Option[java.util.Date])

  val winners = List(Winner(23, List(2, 45, 34, 23, 3, 5)), Winner(54, List(52, 3, 12, 11, 18, 22)))
  val lotto = Lotto(5, List(2, 45, 34, 23, 7, 5, 3), winners, None)

  val json =
    ("lotto" ->
      ("lotto-id" -> lotto.id) ~
      ("winning-numbers" -> lotto.winningNumbers) ~
      ("draw-date" -> lotto.drawDate.map(_.toString)) ~
      ("winners" ->
        lotto.winners.map { w =>
          (("winner-id" -> w.id) ~
           ("numbers" -> w.numbers))}))

  println(compact(render(json)))
}
Comments