Play JSON is a powerful Scala JSON library, originally developed by the Play team for use with Play Framework. It uses Jackson for JSON parsing and has no Play dependencies.
We've provided some documentation here on how to use Play JSON in your app (without Play). For more information on how to use Play JSON in Play, please refer to the Play documentation.
Getting Started
To get started, you can add play-json as a dependency in your project:
Play JSON supports Scala 2.12 and 2.13. Choosing the right JAR is automatically managed in sbt. If you're using Gradle or Maven then you need to use the correct version in the artifactId.
JSON AST
The base type in Play JSON is play.api.libs.json.JsValue, and has several subtypes representing different JSON types:
JsObject: a JSON object, represented as a Map. Can be constructed from an ordered Seq or any kind of Map using JsObject.apply
JsArray: a JSON array, consisting of a Seq[JsValue]
JsNumber: a JSON number, represented as a BigDecimal.
JsString: a JSON string.
JsBoolean: a JSON boolean, either JsTrue or JsFalse.
JsNull: the JSON null value.
The play.api.libs.json package includes several features for constructing JSON from scratch, as well as for converting to and from case classes.
Basic reading and writing
The play.api.libs.json.Json object has several methods for reading and writing:
Json.parse parses a JSON string or InputStream into a JSON tree:
The (json \ "location" \ "lat") returns a JsLookupResult which may or may not contain a value. Note that the get operation is not always safe; it throws an exception if the path doesn't exist.
You can also use \ to look up indices within a JsArray:
Like get, this will throw an exception if the index doesn't exist. Use the Simple Path \ operator and validate or asOpt (described below) if you expect that they key may not be present.
Reading and writing objects
To convert a Scala object to and from JSON, we use Json.toJson[T: Writes] and Json.fromJson[T: Reads] respectively. Play JSON provides the Reads and Writes typeclasses to define how to read or write specific types. You can get these either by using Play's automatic JSON macros, or by manually defining them.
You can also read JSON from a JsValue using validate, as and asOpt methods. Generally it's preferable to use validate since it returns a JsResult which may contain an error if the JSON is malformed.
It is also possible to implement custom logic by implementing the Reads, Writes and/or Format traits manually, but we recommend using the automatic conversion macros or the functional DSL if possible.
Manual JSON construction
JSON can also be manually constructed using a DSL:
请发表评论