I have a case class with many members, two of which are not primitive:
import com.twitter.util.Duration case class Foo( a: Int, b: Int, ..., y: Int, z: Int, timeoutSeconds: Duration, runtimeMinutes: Duration)
I would like to deserialize the following JSON into an instance of this case class:
{ "a": 1, "b": 2, // ... "y": 42, "z": 43, "timeoutSeconds": 30, "runtimeMinutes": 12, }
Usually I just write json.extract[Foo]
. However, I get an obvious MappingException
with this due to timeoutSeconds
and runtimeMinutes
.
I looked at the FieldSerializer
, which allows you to convert fields to AST. However, this is not enough because it allows only AST transformations.
I also looked at the CustomSerializer[Duration]
extension, but there is no way to figure out which JSON keys are processed ( timeoutSeconds
or runtimeMinutes
).
I could also try extending CustomSerializer[Foo]
, but then I will have many code templates to extract the values ββfor a
, b
, ..., z
.
Ideally, I need something that accepts PartialFunction[JField, T]
as a deserializer, so that I can simply write:
{ case ("timeoutSeconds", JInt(timeout) => timeout.seconds case ("runtimeMinutes", JInt(runtime) => runtime.minutes }
and rely on case class deserialization for the rest of the parameters. Is such a design possible in json4s?
Note that this is similar to a combination of type and field serializers , except that I want type deserialization to differ depending on the JSON key.