我一直在使用一些遗留代码而且我遇到了一些麻烦。 我有其他人写的枚举,现在我应该写入数据库中的一些数据并从中读取。这里有一些例子:
这是枚举
object MarketType extends scala.Enumeration {
type MarketType = Value
val Continent, Country, State, City = Value
implicit val marketTypeReads = EnumUtility.enumFormat(MarketType)
}
case class Market(
id: ObjectId = new ObjectId,
name: String,
marketType: Option[MarketType] = None,
)
object Market {
val writes = new Writes[Market] {
def writes(o: Market) = Json.obj(
"id" -> o.id,
"name" -> o.name,
"type" -> o.marketType
)
}
val reads: Reads[Market] = (
(JsPath \ "id").readNullable[ObjectId].map(validateAndFetchObjectId) and
(JsPath \ "name").read[String] and
(JsPath \ "type").read[MarketType]
)(Market.apply _)
implicit val format: Format[Market] = Format(reads, writes)
这是我从前端获取的JSON以及我应该写入数据库的内容:
{"name":"Name","type":"state","description":"Desc"}
答案 0 :(得分:0)
更改此:
val reads: Reads[Market] = (
(JsPath \ "id").readNullable[ObjectId].map(validateAndFetchObjectId) and
(JsPath \ "name").read[String] and
(JsPath \ "type").read[MarketType]
)(Market.apply _)
进入:
val reads: Reads[Market] = (
(JsPath \ "id").readNullable[ObjectId].map(validateAndFetchObjectId) and
(JsPath \ "name").read[String] and
(JsPath \ "type").read[MarketType]
)((id, name, type) => Market(id, name, Some(MarketType.withName(type))))
需要注意的事项:
您发布的JSON的小写type
字段的值为;这将在传递到MarketType.withName()
方法时在生产中抛出NoSuchElement异常。确保API的客户端以Camel case
示例:{ .., type: "State", .. }