tintin
tintin

Reputation: 1519

Scala json object as argument for case class

I have a data source which is saved as json format string. what I want to do is to read every json record as a case class ,I am using json4s as the parser. and use the extract method to get the case class.

my class is like this:

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

case class Order(
  order_id: String,
  buyer_id: String,
  seller_id: Long,
  price: Double
)

and the parsing code is:

file.map(parse(_).extract[Order])

but this is done out of the class, what I want is json string as a constructor function argument for class Order

but as far as I know, a case class constructor must use the default constructor.

so is there anyway to deal with this?

Upvotes: 0

Views: 812

Answers (2)

chengpohi
chengpohi

Reputation: 14217

You maybe also want implicit:

implicit def jsonStrToOrder(s: String): Order = parse(s).extract[Order]
val orders: List[Order] = file

Upvotes: 0

Haspemulator
Haspemulator

Reputation: 11308

You could use companion object for such purposes:

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

case class Order(
  order_id: String,
  buyer_id: String,
  seller_id: Long,
  price: Double
)

object Order {
  def apply(file: File): Order = {
    file.map(parse(_).extract[Order])
  }
}

And then use it like this:

val file = openFile(...)
val order = Order(file)

Upvotes: 2

Related Questions