QuickKnol: Lift Json, ShortTypeHints and Scala Traits

We use the awesome Lift Json library in quite a few our projects. It allows for easy customization and is handy for writing and parsing JSON strings. One of the situations which could possibly push you against the wall is when you have classes extending traits. Let us look at this quick example

We have the situation like above where we have the Reducer trait. The Reducer can have multiple implementations as we have above. Finally, the Analysis class takes the data cube on which it has to work and a list of reductionSteps each one of which is individually a Reducer.

Let us assume that this class comes to us as a JSON string over a REST service. Let us write a test case for JSON write first.

Ok, this one works well. Now, let us try to do the reverse wherein, we get a JSON string and we would try to convert it to an Analysis object.

Interestingly, this blows up with the following error

Here, LiftJSON is not able to identify how it can convert the Reducers to their respective classes as there is no constructor which it can use directly.

Now, is the time to give some hints to the Lift formats. We add the following as hints

Once this is done, let us see what kind of JSON string is generated. As you would notice that now even at the time of creating the JSON string, lift json would add the type hints along

{“dataCubeName”:”TwitterAnalysis”,”reductionSteps”:[{“type”:”EmotionReducer”,”name”:”Emo1″,”coefficientLevel”:0.1},{“type”:”SentimentReducer”,”name”:”Sen1″,”coefficientLevel”:0.5}]}

Now, if we try to re-run the test scenario with the modified string, we would get the object back in the right structure.

If you notice, we have overridden typeHintFieldName. By default, it is jsonClass which isn’t very intuitive so we replaced it with type.

override val typeHintFieldName = “type”

You can find the sample project with the above changes on the Knoldus GitHub account.

Written by 

Vikas is the CEO and Co-Founder of Knoldus Inc. Knoldus does niche Reactive and Big Data product development on Scala, Spark, and Functional Java. Knoldus has a strong focus on software craftsmanship which ensures high-quality software development. It partners with the best in the industry like Lightbend (Scala Ecosystem), Databricks (Spark Ecosystem), Confluent (Kafka) and Datastax (Cassandra). Vikas has been working in the cutting edge tech industry for 20+ years. He was an ardent fan of Java with multiple high load enterprise systems to boast of till he met Scala. His current passions include utilizing the power of Scala, Akka and Play to make Reactive and Big Data systems for niche startups and enterprises who would like to change the way software is developed. To know more, send a mail to hello@knoldus.com or visit www.knoldus.com

Leave a Reply

%d bloggers like this: