Here’s the translation of the JSON handling example from Go to Scala:
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 and Response2 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 to json.Marshal() in Go.
For decoding, we use Json.parse() to parse a JSON string, and then use the \ operator and as[] method to extract values.
Custom type decoding is done using as[Response2] instead of Unmarshal.
For writing JSON directly to output, we use Console.out.println() with Json.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.