concept custom serializer in category scalatra

This is an excerpt from Manning's book Scalatra in Action.
It’s possible to override the default conversion behavior for a type by registering a custom serializer for that type. This is discussed in section 5.3.
The JValue DSL leads to concise code and allows you to produce JSON with little typing overhead. Decomposition doesn’t involve writing any manual conversion code, and it’s good for the average conversion case. It relies on general conventions that may not be suitable in all cases, so you may need to write a custom serializer.
Both approaches can be combined: decomposition can be used in the DSL, and the DSL can be used to write a custom serializer. Now let’s move on and look at how to process JSON.
A custom serializer defines the JSON conversion for a specific type. In the case of a syntactical mismatch between JSON and a Scala type, a custom serializer can help you align the two formats through syntactical and structural transformations. In this section, we’ll look at how you can make use of custom serializers.
What can you do instead? You can write a custom serializer. A custom serializer basically represents two partial functions: one function accepts a JValue and returns a NutritionFacts; the other function knows how to create a NutritionFacts from a JSON document.
The following listing shows how to define a custom serializer for the example. Note that you can use the full power of operations discussed in section 5.2.
Listing 5.13. Custom serializer for NutritionFacts
class NutritionFactsSerializer extends CustomSerializer[NutritionFacts](implicit formats => ({ case jv: JValue => val e = (jv \ "energy").extract[Int] val c = (jv \ "carbohydrate").extract[Double] val f = (jv \ "fat").extract[Double] val p = (jv \ "protein").extract[Double] NutritionFacts( Energy(e), Carbohydrate(c), Fat(f), Protein(p)) }, { case facts: NutritionFacts => ("energy" -> facts.energy.value) ~ ("carbohydrate" -> facts.carbohydrate.value) ~ ("fat" -> facts.fat.value) ~ ("protein" -> facts.protein.value) }))The custom serializer needs to be registered in the implicit Formats value. This can be achieved by using the + operator, which takes a CustomSerializer as an argument and returns a new Formats. The following listing shows an example with two routes using the custom serializer.