Json4s を利用します。最新バージョンはこちらから検索できます。
build.sbt (sbt)
libraryDependencies += "org.json4s" %% "json4s-jackson" % "3.3.0"
pom.xml (maven)
<dependency>
<groupId>org.json4s</groupId>
<artifactId>json4s-jackson_${scala.version}</artifactId>
<version>3.3.0</version>
</dependency>
import org.json4s._
import org.json4s.jackson.JsonMethods._
object Main {
def main(args: Array[String]): Unit = {
val json = """{ "numbers" : [1, 2, 3, 4] }"""
val jsonObj = parse(json)
val map = jsonObj.asInstanceOf[JObject].values
println(map) //=> Map(numbers -> List(1, 2, 3, 4))
println(map get "numbers") //=> Some(List(1, 2, 3, 4))
val json2 = """{ "name" : "Toy", "price" : 35.35 }"""
val jsonObj2 = parse(json2)
val map2 = jsonObj2.asInstanceOf[JObject].values
println(map2) //=> Map(name -> Toy, price -> 35.35)
println(map2 get "price") //=> Some(35.35)
}
}
import org.json4s.jackson.JsonMethods._
import org.json4s.JsonDSL._
object Main {
def main(args: Array[String]): Unit = {
// リストから JSON 文字列に変換
val list = List[Int](1, 2, 3)
println(compact(render(list))) //=> [1,2,3]
// タプルから JSON 文字列に変換
val tuple = ("name" -> "taro")
println(compact(render(tuple))) //=> {"name":"taro"}
// タプルの結合
println(compact(render(
("name" -> "taro") ~ ("age" -> 20) //=> {"name":"taro","age":20}
)))
// Option 型を利用して if 存在するならば、が記述可能
println(compact(render(
("name" -> Some("taro")) ~ ("age" -> (None: Option[Int])) //=> {"name":"taro"}
)))
// 複雑な例
println(compact(render(
("key" ->
("inner_key" -> "value") ~
("inner_key2" -> List(1, 2, 3)))
))) //=> {"key":{"inner_key":"value","inner_key2":[1,2,3]}}
}
}