0

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?

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

You maybe also want implicit:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.