check out the following example:
object MyTrait {
def apply(value: Int): MyTrait = value match {
case 0 => A
case 1 => B
case 2 => C
case _ => C
}
def unapply(arg: MyTrait): Int = arg.value
}
case object A extends MyTrait {
val value = 0
}
case object B extends MyTrait {
val value = 1
}
case object C extends MyTrait {
val value = 2
}
case class Test(value: MyTrait)
implicit val testFormatter = Json.format[Test]
all right, this code won't work because i didn't create a JSON serializer for my type "MyTrait". I could do it the way the Play Framework show us to do in the documentation, but it would make a json looking like
{ value: { whatever: 1 } }
and i would like it to look like
{ value: 1 }
In short, i would like my MyTrait objetcs to be interpreted as primitive types (Int) instead of a nested Json Oject.
If someone could help me with that i would be greatful. Thank you by advance!
The documentation indicates how to provide custom
Writes, there toMyTraitto serialize only it's innervalue.Then when serializing
MyTraitinstances (note the type ascription bellow is required asWritesis invariant):And so about
Testclass:I would rather recommend to have a look at Enumeratum for the enumerated type
MyTrait, or to refactorMyTraitas a Value class and useJson.valueFormatas below.