Search code examples
scalalift-json

Map frequently changing JSON value to corresponding element in Scala


I have a JSON value like

{
    "valType": "Integer",
    "data": 5
}

or

{
    "valType": "Integer",
    "data": [2, 3]
}

or

{
    "valType": "String",
    "data": "value1"
}

or

{
    "valType": "String",
    "data": ["string1", "string2"]
}

value of data key is changing. When I tried to map these in Scala with

class value {
    var valType: String = _
    var data: Any = _
}

using ObjectMapper, it works fine.

But on trying it with lift-json, using class

case class value(valType: String, data: Any) {}

, it is throwing error

Exception in thread "main" net.liftweb.json.MappingException: No usable value for data
No information known about type

How can I resolve same in lift-json?

Vesrion: Scala: 2.11 Lift-json: 2.6


Solution

  • You must write a custom serializer that parses the "value" field different based on the content of the "valType" field.

    How to write a serializer is described in the Serializing non-supported types section of the lift-json readme.