0

json4s allows user to convert a JsonAST object to a case class using extract.

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

implicit val formats = DefaultFormats

case class Item(name: String, price: Double)
val json = parse("""{"name": "phone", "price": 1000.0}""") // JObject(List((name,JString(phone)), (price,JDouble(1000.0))))
val item = json.extract[Item] // Item(phone,1000.0)

However, to convert a case class into a JsonAST object, the only way I can think of is:

  1. serialize a case class using write
  2. deserialize a string using extract

Like below:

parse(write(item)) // JObject(List((name,JString(phone)), (price,JDouble(1000.0))))

Is there any better way for the conversion? Thank you!

yiksanchan
  • 1,890
  • 1
  • 13
  • 37
  • Does this cover what you want? https://stackoverflow.com/questions/22992472/how-to-serialize-object-to-ast-using-json4s – Ethan Sep 13 '18 at 17:35

1 Answers1

1

Extraction.decompose converts a case class object into a JsonAST.

Extraction.decompose(item) // JObject(List((name,JString(phone)), (price,JDouble(1000.0))))
yiksanchan
  • 1,890
  • 1
  • 13
  • 37