说我有以下内容:
[ {
"job_id": "1",
"status": "running"
},
{
"job_id": "0",
"status": "finished"
}]
我可以用json4s以某种方式执行以下操作:
case class Job(job_id: Int, status: JobStatus)
abstract class JobStatus
case class JobFinished extends JobStatus
case class JobRunning extends JobStatus
... some magic is probably needed here
这样提取第一个片段会导致:
[ Job(1, JobRunning()), Job(0, JobFinished())]
答案 0 :(得分:1)
我认为创建基于JSON的scala案例类的最佳方法是使用此站点,这添加了魔法,我通常使用这个站点,你甚至可以更改clases的名称,所以在你的情况下,您可以使用该站点,然后管理类中的关系:
答案 1 :(得分:1)
您可以使用枚举,并通过json4s-ext将EnumSerializer
添加到formats
。
但是,您的枚举将序列化为int(在您的情况下为0或1)。
添加到我自己的答案中,您还可以使用EnumNameSerializer,它将序列化为您指定的枚举值(如“running”或“finished”)。
答案 2 :(得分:1)
这是可能的,但需要一些编码。 我将尝试在一些较小的步骤中将其分解。
// Types
case class Job(jobId: Int, status: JobStatus)
// Sealed trait to make match exhaustive in helper functions
sealed trait JobStatus
// use case object to not create uneeded instances, also case class without () no longer allowed
case object JobFinished extends JobStatus
case object JobRunning extends JobStatus
import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
// helper functions, could be improved by having a mapping
implicit def stringToJobStatus(in: String) : JobStatus = in match {
case "running" => JobRunning
case "finished" => JobFinished
}
implicit def jobStatusToString(jobStatus: JobStatus) : String = jobStatus match {
case JobRunning => "running"
case JobFinished => "finished"
}
// here is the "magic" a custom serializer
class JobSerializer extends CustomSerializer[Job](format => (
// unmarshal Function
{
case JObject( JField("job_id", JString(jobId)) :: JField("status", JString(status)) :: Nil ) => {
new Job(jobId.toInt, status)
}
},
// masrshal Function
{
case Job(jobId, status) => JObject(
JField("job_id", JString(jobId.toString)) ::
JField("status", JString(status)) :: Nil)
}
))
// Implicit formats for serialization and deserialization
implicit val formats = Serialization.formats(NoTypeHints) + new JobSerializer
val data = """
[
{
"job_id": "1",
"status": "running"
},
{
"job_id": "0",
"status": "finished"
}
]
"""
read[List[Job]](data)
res3: List[Job] = List(Job(1,JobRunning), Job(0,JobFinished))
答案 3 :(得分:1)
尽管@Andres Neumann的答案非常好,但它确实需要重新实现整个Job类的序列化(这可能比示例中的Dumbed-down Job类大很多),而唯一的序列化是实际上需要的是状态。基于@ Andreas'回答所需的实际代码有点短,并且不要求Job中的每个字段都要手动序列化。
// here is the "magic" a custom serializer
class JobStatusSerializer extends CustomSerializer[JobStatus](format => (
// unmarshal Function
{
case JString(status) => {
// helper functions, could be improved by having a mapping
def stringToJobStatus(in: String): JobStatus = in match {
case "running" => JobRunning
case "finished" => JobFinished
}
stringToJobStatus(status)
}
},
// marshal Function
{
case status: JobStatus => {
def jobStatusToString(jobStatus: JobStatus): String = jobStatus match {
case JobRunning => "running"
case JobFinished => "finished"
}
JString(jobStatusToString(status))
}
}
)
)