1

I'm looking for suggestions or libraries that can help me convert JSON (with nested structure) from one format to another in Scala.

I saw there are a few JavaScript and Java based solutions. Anything in Scala ?

4
  • 1
    You can use Java classes in Scala. Commented May 19, 2015 at 20:28
  • 1
    What do you mean by "format?" Commented May 19, 2015 at 20:32
  • @DavidEhrmann - By "format" i mean the structure and field names are different in each JSON. Commented May 19, 2015 at 20:47
  • @CaptainMan - Sure I can. Commented May 19, 2015 at 20:48

2 Answers 2

6

I really like the Play JSON library. It's API is very clean and it's very fast even if some parts have a slightly steeper learning curve. You can also use the Play JSON library even if you aren't using the rest of Play.

https://playframework.com/documentation/2.3.x/ScalaJson

To convert JSON to scala objects (and vice versa), Play uses implicits. There is a Reads type which specifies how to convert JSON to a scala type, and a Writes type which specifies how to convert a scala object to JSON.

For example:

case class Foo(a: Int, b: String)

There are a few different routes you can take to convert Foo to JSON. If your object is simple (like Foo), Play JSON can create a conversion function for you:

implicit val fooReads = Json.reads[Foo]

or you can create a custom conversion function if you want more control or if your type is more complex. The below examples uses the name id for the property a in Foo:

implicit val fooReads = (
  (__ \ "id").read[Int] ~
  (__ \ "name").read[String]
)(Foo)

The Writes type has similar capabilities:

implicit val fooWrites = Json.writes[Foo]

or

implicit val fooWrites = (
   (JsPath \ "id").write[Int] and
   (JsPath \ "name").write[String]
)(unlift(Foo.unapply))

You can read more about Reads/Writes (and all the imports you will need) here: https://playframework.com/documentation/2.3.x/ScalaJsonCombinators

You can also transform your JSON without mapping JSON to/from scala types. This is fast and often requires less boilerplate. A simple example:

import play.api.libs.json._    

// Only take a single branch from the input json
// This transformer takes the entire JSON subtree pointed to by 
// key bar (no matter what it is)
val pickFoo = (__ \ 'foo).json.pickBranch

// Parse JSON from a string and apply the transformer
val input = """{"foo": {"id": 10, "name": "x"}, "foobar": 100}"""
val baz: JsValue = Json.parse(input)
val foo: JsValue = baz.transform(pickFoo)

You can read more about transforming JSON directly here: https://playframework.com/documentation/2.3.x/ScalaJsonTransformers

Sign up to request clarification or add additional context in comments.

3 Comments

have you used Spray? If so, what has been your experience between it and Play, in particular with JSON?
I've only played with the Spray JSON library, I've never seriously used it. I remember that it was very similar in spirit and syntax to Play's but that it was not as well documented. It's probably just as good, but I am more used to Play's.
baz.transform does not return JsValue anymore, so the last line does not work.
1

You can use Json4s Jackson. With PlayJson, you have to write Implicit conversions for all the case classes. If the no. of classes are small, and will not have frequent changes while development, PlayJson seems to be okay. But, if the case classes are more, I recommend using json4s. You need to add implicit conversion for different types, so that json4s will understand while converting to json.

You can add the below dependency to your project to get json4s-jackson

"org.json4s" %% "json4s-jackson" % "3.2.11"

A sample code is given below (with both serialization and deserialization):

import java.util.Date
import java.text.SimpleDateFormat

import org.json4s.DefaultFormats
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.{Serialization}

/**
 * Created by krishna on 19/5/15.
 */
case class Parent(id:Long, name:String, children:List[Child])

case class Child(id:Long, name:String, simple: Simple)

case class Simple(id:Long, name:String, date:Date)

object MainClass extends App {
  implicit val formats = (new DefaultFormats {
    override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd")
  }.preservingEmptyValues)
  val d = new Date()
  val simple = Simple(1L, "Simple", d)
  val child1 = Child(1L, "Child1", simple)
  val child2 = Child(2L, "Child2", simple)
  val parent = Parent(1L, "Parent", List(child1, child2))

  //Conversion from Case Class to Json
  val json = Serialization.write(parent)
  println(json)

  //Conversion from Json to Case Class
  val parentFromJson = parse(json).extract[Parent]
  println(parentFromJson)

}

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.