There are many JSON libraries for scala but here we are using play-json which is part of Play framework but also can be used independently.
I am using ammonite repl to try out the json parsing on console.
The first step is going from a JSON string to JsValue objects by parsing the json string. The JsValue tree can be parsed by using \ and \ where
\ selects an element in a JsObject, returning a JsValue
\ selects an element in the entire tree returning a Seq[JsValue]
If we are unsure about the content of JsValue then we can use asOpt which will return a None if deserializing causes and exception.
If we want a boolean then we can use the validate method which returns JsSuccess and JsError
Better to use the validate method to check the parsed json
Convert the JSON structure to scala data model
To read from json we need to define a Reads[T] object for each class which defines how we read each incoming json object for the class.
Reads[T] and Writes[T] objects have to be defined to read and write from json object. If the format for both are same then instead we can use the Format[T] object
Examples of reading some other type of data structures
Handling null values
Handling missing values
This is cause error if name and age are missing in the json data field
Handling validation
The read and readNullable have an implicit parameter which can be used for validation with constraints like email, maxLength, filter, pattern and more …