我有这样的模型来解析db到json的结果在休息时api与akka-http
case class Category(id: Long,
title: String,
slug: String,
image: String,
parentId: Long,
createdAt: Timestamp) extends BaseEntity
object Category extends DefaultJsonProtocol with SprayJsonSupport {
implicit object TimestampFormat extends RootJsonFormat[Timestamp] {
val format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
def write(obj: Timestamp) = JsString(format.format(obj.getTime))
def read(json: JsValue) = json match {
case JsString(s) => new Timestamp(format.parse(s).getTime)
case _ => throw DeserializationException("Date expected")
}
}
implicit object ObjectJsonFormat extends RootJsonFormat[Category] {
val format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
def write(obj: Category) = JsObject(Map(
"id" -> JsNumber(obj.id),
"title" -> JsString(obj.title),
"slug" -> JsString(obj.slug),
"image" -> JsString(obj.image),
"parentId" -> JsNumber(obj.parentId),
"createdAt" -> JsString(format.format(obj.createdAt.getTime))
))
def read(value: JsValue): Category = value.convertTo[Category]
}
implicit val objectFormat = jsonFormat6(Category.apply)
}
case class CategoryResponse(status: Int, result: Category)
object CategoryResponse extends DefaultJsonProtocol with SprayJsonSupport {
implicit val objectFormat = jsonFormat2(CategoryResponse.apply)
}
但是如果case类的成员数超过4,则json对象的位置成员与case类的位置不一样。结果就像这样
{
"status": 1,
"result": {
"image": "https://yt3.ggpht.com/-Fq_uiT7y10k/AAAAAAAAAAI/AAAAAAAAAAA/YzIf8sfr7sI/s88-c-k-no-mo-rj-c0xffffff/photo.jpg",
"slug": "news",
"id": 3,
"createdAt": "2016-11-23 14:09:45",
"title": "news",
"parentId": 1
}
}
如何像这样设置位置成员json对象
{
"status": 1,
"result": {
"id": 3,
"title": "news",
"slug": "news",
"image": "https://yt3.ggpht.com/-Fq_uiT7y10k/AAAAAAAAAAI/AAAAAAAAAAA/YzIf8sfr7sI/s88-c-k-no-mo-rj-c0xffffff/photo.jpg",
"parentId": 1,
"createdAt": "2016-11-23 14:09:45"
}
}