在整理到json时,让子案例类无法识别具有父特征的项时遇到了一些麻烦。
我想创建一堆从同一个父母那里继承下来的孩子。像这样:
Parent
trait Parent {
val parentValue: BigDecimal = ??? // This value may be obtained through a database call
val adjusted = {
if (parentValue > 5) { parentValue * 0.12 }
else { parentValue }
}
}
有一些共同的领域:
case class ChildA(field1: Int)
// companion obj
object ChildA {
implicit val jsWriter = new Writes[ChildA] {
def writes(model: ChildA): Jsvalue = {
Json.obj(
"parent" -> model.parentValue,
"child-type" -> model.getClass.getSimpleName,
"child-field-1" -> model.field1, // for ChildB, there would need to be a child-field-2
"adjusted" -> model.adjusted
)
}
}
当我编组到Json时,我定义了一个自定义jswriter:
val a = ChildA(6)
Json.toJson[ChildA](a)
(另一个问题,但是我如何让子级继承父级的json编写器,以便我可以为父级写一个JsWriter并仅添加子级字段而不必为每个子级编写自定义编组器?)>
我可以像这样将其编组到json:
val a = ChildA(6)
val b = ChildB(6, 7)
Json.toJson[Parent](a) // json of ChildA
Json.toJson[Parent](b) // json of ChildB
但是最终,我想创建一个通用输出,以便可以执行以下操作:
[
{
"appiumVersion":"1.8.1",
"buildTag": "build-0",
"newCommandTimeout": "30",
"deviceName":"Samsung Galaxy S9 WQHD GoogleAPI Emulator",
"deviceOrientation":"portrait",
"browserName":"",
"platformName":"Android",
"platformVersion":"7.1",
"app":"sauce-storage:ApiDemos-debug.apk"
},
{
"appiumVersion":"1.8.1",
"buildTag": "build-0",
"newCommandTimeout": "30",
"deviceName":"Samsung Galaxy S9 WQHD GoogleAPI Emulator",
"deviceOrientation":"portrait",
"browserName":"",
"platformName":"Android",
"platformVersion":"7.0",
"app":"sauce-storage:ApiDemos-debug.apk"
}
]
我觉得这是使用更高种类或通用类型的机会。谁能告诉我该怎么做?
答案 0 :(得分:0)
但是您没有从Parent继承ChildA和B。
case class ChildA(field1: Int) extends Parent