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.