Json in Scala
Here’s the translation of the JSON handling example from Go to Scala:
import play.api.libs.json._
import scala.io.StdIn
// We'll use these two case classes to demonstrate encoding and
// decoding of custom types below.
case class Response1(page: Int, fruits: List[String])
case class Response2(page: Int, fruits: List[String])
object JsonExample {
def main(args: Array[String]): Unit = {
// First we'll look at encoding basic data types to
// JSON strings. Here are some examples for atomic values.
println(Json.toJson(true))
println(Json.toJson(1))
println(Json.toJson(2.34))
println(Json.toJson("gopher"))
// And here are some for lists and maps, which encode
// to JSON arrays and objects as you'd expect.
val slcD = List("apple", "peach", "pear")
println(Json.toJson(slcD))
val mapD = Map("apple" -> 5, "lettuce" -> 7)
println(Json.toJson(mapD))
// The JSON library can automatically encode your
// custom data types.
val res1D = Response1(1, List("apple", "peach", "pear"))
println(Json.toJson(res1D))
val res2D = Response2(1, List("apple", "peach", "pear"))
println(Json.toJson(res2D))
// Now let's look at decoding JSON data into Scala
// values. Here's an example for a generic data structure.
val jsonStr = """{"num":6.13,"strs":["a","b"]}"""
val json: JsValue = Json.parse(jsonStr)
// We can access fields using pattern matching
val num = (json \ "num").as[Double]
println(num)
val strs = (json \ "strs").as[List[String]]
val str1 = strs.head
println(str1)
// We can also decode JSON into custom data types.
val str = """{"page": 1, "fruits": ["apple", "peach"]}"""
val res = Json.parse(str).as[Response2]
println(res)
println(res.fruits.head)
// In Scala, we can also write JSON directly to output streams.
// Here's an example writing to standard output.
val d = Map("apple" -> 5, "lettuce" -> 7)
Console.out.println(Json.toJson(d))
}
}
This Scala code demonstrates JSON encoding and decoding using the Play JSON library, which is a popular choice for JSON manipulation in Scala. Here’s a breakdown of the translation:
We import the necessary Play JSON library components.
We define case classes
Response1
andResponse2
instead of structs.The
main
function is wrapped in an object, which is Scala’s equivalent of a static context.We use
Json.toJson()
for encoding values to JSON, which is similar tojson.Marshal()
in Go.For decoding, we use
Json.parse()
to parse a JSON string, and then use the\
operator andas[]
method to extract values.Custom type decoding is done using
as[Response2]
instead ofUnmarshal
.For writing JSON directly to output, we use
Console.out.println()
withJson.toJson()
.
Note that Scala’s JSON handling is typically more functional and type-safe compared to Go’s. The Play JSON library provides a DSL for working with JSON that’s idiomatic to Scala.
To run this program, you would need to have the Play JSON library in your classpath. You can add it to your project using SBT or other Scala build tools.