I have a Scala web service which accepts JSON from a UI.
The user input contains nested logical objects which I want to extract cleanly. For example, I have a User data model, which in turn contains an Address data model.
I want to turn the incoming JSON directly into my target Scala data model but I am seeing errors like org.json4s.package MappingException: No usable value ...
Let’s walk thru a solution. Here’s our Scala data model as discussed above:
The UI returns the following JSON to our Scala http server:
in our Scala app, we have brought in the following json4s dependencies (build.gradle format):
OK! Let’s try to parse this JSON:
What’s happening here is that json4s does not know how to serialize or deserialize our nested case class. The solution is to implement a CustomSerializer serdes.
It is pretty straightforward. We need to supply an implementation for converting from a JObject to an Address instance, and then from an Address instance back to a JObject. Here’s how that looks:
Now we just need to update the implicit Formats which is in scope for the serdes work:
Now, we are able to work with Nested Case Classes and Json using json4s