How do you work with JSON in Scala?
Instruction: Describe methods for parsing and generating JSON in Scala.
Updated
Use a JSON library for parsing, encoding and decoding, and distinguish these steps from domain validation. Circe and Play JSON can each support both directions; using one to read and another to write is not inherently necessary.
With Circe, parse(raw) returns either a parsing failure or a JSON tree. A Decoder[User] converts a suitable tree into a User; decode[User](raw) combines parsing and decoding and reports errors through Either. An Encoder[User] converts a user to a JSON tree, which can be rendered as text, for example with noSpaces. Use modules and derivation syntax compatible with the project's Scala version. Parsing JSON, Custom codecs
For a user with a required string name and positive integer ID, consider three distinct failures: malformed JSON syntax, an ID encoded with the wrong type, and a structurally valid integer ID that violates the positive-ID rule. A derived decoder can help with the structural mapping, but domain rules need a validating decoder or a separate validated constructor. Return a useful error path or message without silently substituting a default user.
Choose and document policies for missing fields, explicit nulls, unknown fields, numeric ranges, time formats and schema evolution. Do not assume every decoder rejects extra fields or that an optional field distinguishes missing from null. Test those behaviors for the chosen codec. Play JSON offers the analogous Reads, Writes and Format abstractions. Play JSON basics
Generate JSON through an encoder rather than string interpolation: quotes, backslashes and control characters need correct escaping. Test valid round trips, malformed input, missing/wrong-type fields, escaped text, large numbers and compatibility with older payloads. Bound request size and nesting for untrusted input, and avoid exposing sensitive payloads in logs. JSON decoding is data validation, not authentication or authorization.